現(xiàn)在人們對于網(wǎng)站的讀取速度是相當?shù)闹匾暎绻粋€網(wǎng)站打開的時間很慢,將會流失很多的瀏覽量和客戶,尤其是相對于動態(tài)網(wǎng)站來說,動態(tài)網(wǎng)站刷新一次或新打開的時候是比較慢的,但靜態(tài)頁面就快很多了,但靜態(tài)頁面也有不足的地方就是不能更新東西,現(xiàn)在我們就來講講如何把動態(tài)網(wǎng)站轉(zhuǎn)化成靜態(tài)網(wǎng)頁,然后時間到了自動刪除的效果。
1.使用php文件讀寫功能與ob緩存機制生成靜態(tài)頁面
比如某個課程的動態(tài)詳情頁地址,
那么這里我們根據(jù)這個地址讀取一次這個詳情頁的內(nèi)容,然后保存為靜態(tài)頁,下次有人訪問這個商品詳情頁動態(tài)地址時,我們可以
直接把已生成好的對應靜態(tài)內(nèi)容文件輸出出來。
<!--?php
$gid=$_GET['gid']+0;//商品id
$goods_statis_file="goods_file_".$gid.".html";//對應靜態(tài)頁文件
$expr=3600*24*10;//靜態(tài)文件有效期,十天
if(file_exists($goods_statis_file)){
$file_ctime=filectime($goods_statis_file);//文件創(chuàng)建時間
if($file_ctime+$expr-->time()){//如果沒過期
echofile_get_contents($goods_statis_file);//輸出靜態(tài)文件內(nèi)容
exit;
}else{//如果已過期
unlink($goods_statis_file);//刪除過期的靜態(tài)頁文件
ob_start();
//從數(shù)據(jù)庫讀取數(shù)據(jù),并賦值給相關(guān)變量
//include("xxx.html");//加載對應的商品詳情頁模板
$content=ob_get_contents();//把詳情頁內(nèi)容賦值給$content變量
file_put_contents($goods_statis_file,$content);//寫入內(nèi)容到對應靜態(tài)文件中
ob_end_flush();//輸出商品詳情頁信息
}
}else{
ob_start();
//從數(shù)據(jù)庫讀取數(shù)據(jù),并賦值給相關(guān)變量
//include("xxx.html");//加載對應的商品詳情頁模板
$content=ob_get_contents();//把詳情頁內(nèi)容賦值給$content變量
file_put_contents($goods_statis_file,$content);//寫入內(nèi)容到對應靜態(tài)文件中
ob_end_flush();//輸出商品詳情頁信息
}
?>
2.使用nosql從內(nèi)存中讀取內(nèi)容(其實這個已經(jīng)不算靜態(tài)化了而是緩存);
以memcache為例:
<!--?php
$gid=$_GET['gid']+0;//商品id
$goods_statis_content="goods_content_".$gid;//對應鍵
$expr=3600*24*10;//有效期,十天
$mem=newMemcache;
$mem--->connect('memcache_host',11211);
$mem_goods_content=$mem->get($goods_statis_content);
if($mem_goods_content){
echo$mem_goods_content;
}else{
ob_start();
//從數(shù)據(jù)庫讀取數(shù)據(jù),并賦值給相關(guān)變量
//include("xxx.html");//加載對應的商品詳情頁模板
$content=ob_get_contents();//把詳情頁內(nèi)容賦值給$content變量
$mem->add($goods_statis_content,$content,false,$expr);
ob_end_flush();//輸出商品詳情頁信息
}
?>
以上就是關(guān)于PHP動態(tài)網(wǎng)頁轉(zhuǎn)化為靜態(tài)網(wǎng)頁的內(nèi)容了,快去試試吧。