1 <?php 2 3 //接收新闻id,传统的方法查询数据库并显示数据 4 $id=intval($_GET['id']); 5 //先判断该新闻对于的静态页面是否存在,如果有,则直接返回,如果 6 //没有,则查询 7 $html_file="news-id".$id.".html"; 8 //filemtime($html_file)+30>=time() 保证文件是30秒有效 9 if(file_exists($html_file) && filemtime($html_file)+30>=time()){ 10 echo '静态页面'; 11 echo file_get_contents($html_file); 12 exit; 13 } 14 //这里大家可以使用工具类完成. 15 $con=mysql_connect("localhost","root","root"); 16 if(!$con){ 17 die("连接失败"); 18 } 19 mysql_select_db("newssys",$con); 20 $sql="select * from news where id=$id"; 21 $res=mysql_query($sql,$con); 22 //显示新闻的内容. 23 if($row=mysql_fetch_assoc($res)){ 24 ob_start();//启动ob缓存 25 header("content-type:text/html;charset=utf-8"); 26 echo "<head><meta http-equiv='content-type' content='text/html;charset=utf-8'/></head>"; 27 echo "<table border='1px' bordercolor='green' cellspacing='0' width=400px height=200px>"; 28 echo "<tr><td>新闻详细内容</td></tr>"; 29 echo "<tr><td>{$row['title']}</td></tr>"; 30 echo "<tr><td>{$row['content']}</td></tr>"; 31 echo "</table>"; 32 $ob_str=ob_get_contents(); 33 //把ob_str保存到一个静态文件页面. 34 //取文件名有讲究 a. 唯一标识该新闻 b. 利用seo 35 file_put_contents("news-id".$id.".html",$ob_str); 36 37 }
页面静态化方式:1.使用缓存,2.使用模板引擎