方案:使用模板替换技术(没有时间延迟)
	  
		|  代码如下 | 
		复制代码 | 
	  
	  
		| 
 /* 
|------------------ 
|  
|------------------ 
*/ 
$oper = $_POST['oper'];//添加操作 
if($oper === 'add') 
{ 
    $title = $_POST['title']; 
    $content = $_POST['content']; 
     
    //如果严格按MVC,这里应该调用model了 
    $con = mysql_connect('localhost', 'root', '123456'); 
    if(!$con) 
    { 
        die('连接失败!'); 
    } 
    mysql_select_db('news', $con); 
    $sql = "insert into question(null, '$title', '$content', '')"; 
    if(mysql_query($sql, $con)) 
    { 
        //1.生成静态文件  
        $id = mysql_insert_id(); 
        $html_filename = 'news-id'.$id.'.html'; 
        $html_fp = fopen($html_filename, 'w'); 
         
        //2.把模板文件读取(news.html) 
        $fp = fopen('news.tpl', 'r'); 
        //r 只读方式打开; r+ 读写方式打开; w 写入方式打开:文件内容将被清空!如果文件不存在将创建; a 以追加的方式打开 
         
        //3.循环读取 
        //如果没有读到文件的最后,就一直读取 
        while(!feof($fp)) 
        { 
            //一行行读 
            $row = fgets($fp); 
            //把占位符替换掉 => 可以自定义完整的替换规则函数 
            $row = str_replace('%title%', $title, $row);//如果不重新赋值$row, $row值不会改变 
            $row = str_replace('%content%', $content, $row); 
             
            fwrite($html_fp, $row);//4.将内容写入静态文件 
        } 
        //5.文件必须关闭 
        fclose($html_fp); 
        fclose($fp); 
         
        echo "添加成功。"; 
    } 
    else 
    { 
        die('添加失败!'); 
    } 
} 
//此时在新闻列表内,点击查看详情的链接,可以改成生成的静态页面地址,直接进入静态文件。 
//news.tpl模板文件 
/* 
 
     
 
        
 
        %title%
 
     
     
        %title%
 
        %content% 
 
     
 
*/
 | 
	  
	
方案:如果静态文件存在,且生成时间30秒内,直接返回静态页面(有时间延迟)
	  
		|  代码如下 | 
		复制代码 | 
	  
	  
		| 
 /* 
|------------------ 
|  
|------------------ 
*/ 
header('content-type:text/html;charset=utf-8'); 
$id = $_GET['id'] ? intval($_GET['id']) : ''; 
if($id === '') die('请输入要查询的新闻id!'); 
$html_file = "news-id-".$id.".html"; 
//1.主要代码 
if(file_exists($html_file) && filemtime($html_file) + 30 >= time()) 
{ 
    echo '静态页面:'; 
    echo file_get_contents($html_file);exit; 
} 
//这里也可以使用DB工具类 
$con = mysql_connect('localhost', 'root', '123456'); 
if(!$con) 
{ 
    die('连接失败!'); 
} 
mysql_select_db('testdb', $con); 
$sql = "select * from bo_question where question_id = $id"; 
$res = mysql_query($sql, $con); 
if($row = mysql_fetch_assoc($res)) 
{ 
    ob_start();//2.启动ob缓存 
    header('content-type:text/html;charset=utf-8'); 
    echo ' '; 
    echo ''; 
    echo '| 问题详细内容 |  '; 
    echo "| 标题:{$row['question_title']} |  "; 
    echo "| 详细:{$row['question_detail']} |  "; 
    echo ' '; 
    $ob_str = ob_get_contents(); 
    //3.把ob_str保存到一个静态文件页面,取文件名有讲究:1.唯一标识该新闻 2.利于seo 
    file_put_contents("news-id-".$id.".html", $ob_str); 
   
  //关闭数据库连接(非必须; 非长连接下,脚本执行完会自动关闭)  
  mysql_close($con); 
}else{ 
    echo '没有查询到资源!'; 
}
 | 
	  
	
从上面看我们头一种生成静态页面的方法更合适于页面的后期维护哦,后者是比较难维护的哦,推荐使用第一种办法。