How do I add PHP code/file to HTML(.html) files?

后端 未结 12 2097
栀梦
栀梦 2020-11-21 22:05

I can\'t use PHP in my HTML pages. For example, index.html. I\'ve tried using both:

 

and



        
相关标签:
12条回答
  • 2020-11-21 22:35

    You can't run PHP in .html files because the server does not recognize that as a valid PHP extension unless you tell it to. To do this you need to create a .htaccess file in your root web directory and add this line to it:

    AddType application/x-httpd-php .htm .html
    

    This will tell Apache to process files with a .htm or .html file extension as PHP files.

    0 讨论(0)
  • 2020-11-21 22:39

    For having .html files parsed as well, you need to set the appropriate handler in your server config.

    For Apache httpd 2.X this is the following line

    AddHandler application/x-httpd-php .html
    

    See the PHP docu for information on your specific server installation.

    0 讨论(0)
  • 2020-11-21 22:41

    AJAX is also a possibility. Effectively you would want data from the php page. Once you have the data you can format in anyway in javascript and display.

    var xmlhttp = new XMLHttpRequest();
    var url = "risingStars.php";
    
    xmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            getDbData(this.responseText);
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
    
    
    function getDbData(response) {
    
    //do whatever you want with respone
    }
    
    0 讨论(0)
  • 2020-11-21 22:41

    For combining HTML and PHP you can use .phtml files.

    0 讨论(0)
  • 2020-11-21 22:50

    If you only have php code in one html file but have multiple other files that only contain html code, you can add the following to your .htaccess file so it will only serve that particular file as php.

    <Files yourpage.html>
    AddType application/x-httpd-php .html 
    //you may need to use x-httpd-php5 if you are using php 5 or higher
    </Files>
    

    This will make the PHP executable ONLY on the "yourpage.html" file and not on all of your html pages which will prevent slowdown on your entire server.

    As to why someone might want to serve php via an html file, I use the IMPORTHTML function in google spreadsheets to import JSON data from an external url that must be parsed with php to clean it up and build an html table. So far I haven't found any way to import a .php file into google spreadsheets so it must be saved as an .html file for the function to work. Being able to serve php via an .html file is necessary for that particular use.

    0 讨论(0)
  • 2020-11-21 22:52

    You can modify .htaccess like others said, but the fastest solution is to rename the file extension to .php

    0 讨论(0)
提交回复
热议问题