比如某個商品的動態詳情頁地址是: 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();//輸出商品詳情頁信息
}
?>