Home  >  Article  >  php教程  >  General PHP code to dynamically generate static HTML web pages

General PHP code to dynamically generate static HTML web pages

高洛峰
高洛峰Original
2016-12-21 11:35:131296browse

We know that when PHP reads MYSQL for dynamic display, there will be many performance problems when the traffic is large. If you rent someone else's virtual host, the CPU will be restricted due to excessive CPU consumption, resulting in inaccessible web pages. Here I will give you a method for dynamically generating HTML in PHP, which can greatly reduce the server CPU load.

First, set up the .htaccess file to convert dynamically called parameters into static HTML URL addresses. For example, forward the files in the post directory to the wp-post.php file in the root directory. Add statements similar to:

RewriteRule ^post/([a-z0-9-]+.html)$ wp-post.php?$1$2

  Then modify the wp-post.php file and add the following PHP code at the beginning of the file:

ob_start(); 
$qstring = isset($_SERVER[%26quot;QUERY_STRING%26quot;]) ? $_SERVER[%26quot;QUERY_STRING%26quot;] : %26quot;%26quot;; 
define(%26quot;HTML_FILE%26quot;, $_SERVER['DOCUMENT_ROOT'].%26quot;/post/%26quot;.$qstring); 

if (file_exists(HTML_FILE)) 
{ 
$lcft = filemtime(HTML_FILE); 
if (($lcft + 3600) %26gt; time()) //判断上次生成HTML文件是否超过1小时,若没有才直接输出文件内容 
{ 
echo(file_get_contents(HTML_FILE)); 
exit(0); 
} 
}

Next is the existing PHP code, and then add the following PHP code at the end of the current code:

define(%26quot;HTMLMETA%26quot;,%26quot;%26lt;!-- this is a real static html file created at %26quot;.date(%26quot;Y-m-d H:i:s%26quot;).%26quot; --%26gt;%26quot;); 
$buffer = ob_get_flush(); 
$fp = fopen(HTML_FILE, %26quot;w%26quot;); 
if ($fp) 
{ 
fwrite($fp, $buffer.HTMLMETA); 
fclose($fp); 
}

 Okay, then check your static HTML page. If a comment line appears at the end of the page, it means it has been successfully created. static HTML files.

One application of this method is the WordPress Annual Blog Statistics Plug-in that I wrote earlier. Since this statistics plug-in queries the database more than ten times, there will be big performance problems when many people access it. I will introduce how to use it. After using this dynamic HTML generation technology, it can query once a day and generate statistical rankings, which perfectly solves the performance problem of querying the database.


For more general PHP code to dynamically generate static HTML web pages and related articles, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn