使用ob缓冲技术实现页面真静态

例子

<?php

   //使用ob缓冲技术实现页面真静态  减少数据库的访问,第一次读取数据库,后面直接请求静态页面
    $filename='ob.html';  //定义静态页面的文件名称
//判断静态页面是否存在,如果静态页面存在直接读取静态页面的内容,否则查询数据库 file_exists() 判断文件是否存在
//让静态页面每隔5分钟改变一次,也意味着5分钟把静态页面的内容改变(从数据库中重新查询数据)filemtime()文件最后修改的时间
if(file_exists($filename)&&(time()-filemtime($filename))<300){
  $str=file_get_contents($filename);
  echo $str;
  die;
}
   $pdo=new PDO('mysql:host=localhost;dbname=study7','root','root');
   $pdo->exec("set names utf8");
   $sql="select * from test";
   echo 'hello world';
   $data=$pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
   ob_start(); //开启ob缓冲
 ?>
 <!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" xml:lang="en">
 <head>
  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
  <title></title>
 </head>
 <body>
  <table border='1'>
 <tr>
  <th>编号</th>
  <th>标题</th>
  <th>操作</th>
 </tr>
 <?php foreach($data as $v){?>
 <tr>
  <td><?php echo $v['id'] ?></td>
  <td><?php echo $v['title'] ?></td>
  <td><a href="detail.php?id=<?php echo $v['id'] ?>">显示详情</a><a href="">删除</a><a href="">修改</a></td>
 </tr>
 <?php  } ?>
</table>
 </body>
 </html>
 <?php   
   //获取ob缓冲中的内容
   $str=ob_get_contents();
   file_put_contents($filename,$str);
 ?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值