Home > Article > Backend Development > PHP generates static HTML for the entire website_PHP tutorial
In fact, the method of implementation is very simple.
php;"> <?php //在你的开始处加入 ob_start(); ob_start(); //以下是你的代码 //在结尾加入 ob_end_clean(),并把本页输出到一个变量中 $temp = ob_get_contents(); ob_end_clean(); //写入文件 $fp = fopen(‘文件名’,'w’); fwrite($fp,$temp) or die(‘写文件错误’); ?>
This is only the most basic method and is not very practical, because the website needs to be updated and the HTML needs to be regenerated regularly
Here’s the method I use:
if(file_exists("xxx.html"))
{
$time = time();
//If the file modification time is less than half an hour different from the current time, it will be directed to the html file, otherwise the html will be regenerated
if($time - filemtime("xxx.html") < 30*60)
{
header("Location:xxx.html");
}
}
//Add ob_start() at your beginning;
ob_start();
//Details of the page
//Add ob_end_clean() at the end and output this page to a variable
$temp = ob_get_contents();
ob_end_clean();
//Write file
$fp = fopen(‘xxx.html’,’w’);
fwrite($fp,$temp) or die(‘Write file error’);
//Redirect
header("Location:xxx.html");
The following is an introduction to some functions used:
1. Flush: refresh the contents of the buffer and output.
Function format: flush()
Description: This function is frequently used and is very efficient.
2. ob_start: Open the output buffer
Function format: void ob_start(void)
Note: When the buffer is activated, all non-file header information from the PHP program will not be sent, but will be saved in the internal buffer. In order to output the contents of the buffer, you can use ob_end_flush() or flush() to output the contents of the buffer.
3. ob_get_contents: Returns the contents of the internal buffer.
Usage: string ob_get_contents(void)
Description: This function will return the contents of the current buffer. If the output buffer is not activated, it will return FALSE.
4. ob_get_length: Returns the length of the internal buffer.
Usage: int ob_get_length(void)
Description: This function will return the length in the current buffer; like ob_get_contents, if the output buffer is not activated. then returns FALSE.
5. ob_end_flush: Send the contents of the internal buffer to the browser and close the output buffer.
Usage: void ob_end_flush(void)
Description: This function sends the contents of the output buffer (if any).
6. ob_end_clean: Delete the contents of the internal buffer and close the internal buffer
Usage: void ob_end_clean(void)
Description: This function will not output the contents of the internal buffer but delete it!
7. ob_implicit_flush: Turn on or off absolute refresh
Usage: void ob_implicit_flush ([int flag])
Note: Anyone who has used Perl knows the meaning of $|=x. This string can open/close the buffer, and the ob_implicit_flush function is the same as that. The default is to close the buffer. After turning on absolute output, each script output Send directly to the browser, no need to call flush()