Method analysis using PHP's ob_start to generate static pages

  • 2020-03-31 21:34:33
  • OfStack

Although the method is a lot of, but it is simple to use, I think it is still the first to determine the generation of the page file has been generated and the existing time between the difference between the value, if you meet a certain value to start to generate, this method is relatively easy, not to say, start!

Let's mention three functions before we start :"ob_start(), ob_end_clean(), ob_get_contents()"

Ob_start (): opens the buffer to cache the contents of the static file you need to generate.
Ob_get_contents (): reads the contents of the buffer.
Ob_end_clean (): this is important because the contents of the buffer are not read until this function is used. Copy contents to clipboard code:
 
if(file_exists("./index.htm"))//See if the static index.htm file exists
{ 
$time=time(); //What is the difference between the file modification time and the current time? Direct to the HTM file, otherwise rebuild HTM
if($time-filemtime("./index.htm")< 600) 
{ 
header("Location:classhtml/main.htm"); } 
} 

//Add ob_start() to your start; CHINAZ

//Home page content, is your dynamic part

//Add ob_end_clean() at the end and output the page to a variable
$temp=ob_get_contents(); 
ob_end_clean(); 

//Written to the file
$fp=fopen("./index.htm",'w'); 
fwrite($fp,$temp) or die(' Writing error '); 
//Echo "HTML is generated!" ;


Example code:
 
<?php 
ob_start(); 
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title><?php echo ' Programming navigation  dh.jb51.net';?></title> 
</head> 

<body> 
<?php echo "dh.jb51.net";?> 
</body> 
</html> 
<?php 
$cacheStr=ob_get_contents(); 
$handle=fopen("jb51.html","w"); 
fwrite($handle, $cacheStr); 
ob_clean(); 
?> 

Related articles: