PHP生成静态HTML页面的方法

1.使用PHP文件读写功能与ob缓存机制生成静态页面
比如某个商品的动态详情页地址是: http://xxx.com?goods.php?gid=112
那么这里我们根据这个地址读取一次这个详情页的内容,然后保存为静态页,下次有人访问这个商品详情页动态地址时,我们可以
直接把已生成好的对应静态内容文件输出出来。

<!--?php
$gid = $_GET['gid']+0;//商品id
$goods_statis_file = "goods_file_".$gid.".html";//对应静态页文件
$expr = 3600*24*10;//静态文件有效期,十天
if(file_exists($goods_statis_file)){
  $file_ctime =filectime($goods_statis_file);//文件创建时间 
     if($file_ctime+$expr-->time()){//如果没过期
      echo file_get_contents($goods_statis_file);//输出静态文件内容
         exit;
     }else{//如果已过期
         unlink($goods_statis_file);//删除过期的静态页文件
         ob_start();
  
            //从数据库读取数据,并赋值给相关变量
  
            //include ("xxx.html");//加载对应的商品详情页模板
  
            $content = ob_get_contents();//把详情页内容赋值给$content变量
            file_put_contents($goods_statis_file,$content);//写入内容到对应静态文件中
            ob_end_flush();//输出商品详情页信息
     }
}else{
 ob_start();
  
 //从数据库读取数据,并赋值给相关变量
  
 //include ("xxx.html");//加载对应的商品详情页模板
  
 $content = ob_get_contents();//把详情页内容赋值给$content变量
 file_put_contents($goods_statis_file,$content);//写入内容到对应静态文件中
 ob_end_flush();//输出商品详情页信息
  
}
?>


2.使用nosql从内存中读取内容(其实这个已经不算静态化了而是缓存);
以memcache为例:

<!--?php
$gid = $_GET['gid']+0;//商品id
$goods_statis_content = "goods_content_".$gid;//对应键
$expr = 3600*24*10;//有效期,十天
  
$mem = new Memcache; 
$mem--->connect('memcache_host', 11211);
  
$mem_goods_content = $mem->get($goods_statis_content);
  
if($mem_goods_content){
  echo $mem_goods_content;
}else{
 ob_start();
  
 //从数据库读取数据,并赋值给相关变量
  
 //include ("xxx.html");//加载对应的商品详情页模板
  
 $content = ob_get_contents();//把详情页内容赋值给$content变量
 $mem->add($goods_statis_content,$content, false, $expr);
 ob_end_flush();//输出商品详情页信息
  
}
  
?>
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值