[TOC]
## 什么是動態語言靜態化
將現有PHP等動態語言的邏輯代碼生成為靜態HTML文件,用戶訪問動態腳本重定向到靜態HTML文件的過程。
對實時性要求不高的頁面
## 為什么要靜態化
動態腳本通常會做邏輯計算和數據查詢,訪問量越大,服務器壓力越大
訪問量大時可能會造成CPU負載過高,數據庫服務器壓力過大
## 靜態化的實現方式
### 使用模板引擎
可以使用 Smarty的緩存機制生成靜態HTML緩存文件
```
$smarty-> cache dir=$RooT."/ cache";/緩存目錄
$smarty-> caching=true;//是否開啟緩存
$smarty-> cache_lifetime="3600";/緩存時間
$smarty-> display(string template, string cache_id[, string compile_id]]):
$smarty-> clear_all_cache();//清除所有緩存
$smarty-> clear_cache(" file.html");/清除指定的緩存
$smarty-> clear_cache( 'article.htm',$art_id);//清除同一個模板下的指定緩存號的緩存
```
### 利用ob系列的函數
```
ob_start():打開輸出控制緩沖
ob_get_contents0:返回輸出緩沖區內容
ob_clean():清空輸出緩沖區
ob_end_flush0:沖刷出(送出)輸出緩沖區內容并關閉緩沖
```
```
ob_start():
//輸出到頁面的HTML代碼
...
ob_get_contents();
ob end flush();
fopen(); //寫入
```
實現頁面靜態化,并且當內容改變時,主動緩存新內容,且如果有$_ GET參數時候,帶參數的靜態化頁面
```
<?php
$id = $_GET['id'];
if (empty($id)) {
$id = '';
}
$cache_name = md5(__FILE__) . '-' . $id . '.html';
$cache_lifetime = 3600;
if (@filectime(__FILE__) <= @filectime($cache_name) && file_exists($cache_name) && $cache_lifetime+@filectime($cache_name) > time()) {
include $cache_name;
exit;
}
ob_start();
?>
<b>This is My script <?php echo $id; ?></b>
<?php
$content = ob_get_contents();
ob_end_flush();
file_put_contents($cache_name, $content);
?>
```