靜態化能大幅降低伺服器負載、提升前端效能。本文介紹原生 Output Control 函數與 ThinkPHP 內建 buildHtml() 兩種實作方式。
核心函數:ob_start() 開啟緩衝 → ob_get_contents() 取得內容 → ob_end_clean() 關閉並清空。
<?php
ob_start(); // 1. 開啟緩衝,前方不可有任何輸出
echo '<html><head><title>靜態頁面</title></head><body>內容</body></html>';
$content = ob_get_contents(); // 2. 取得緩衝內容
ob_end_clean(); // 3. 關閉緩衝
$fp = fopen('static_page.html', 'w');
fwrite($fp, $content);
fclose($fp);
echo '生成成功';
?>
ThinkPHP 2.x/3.x 內建方法,自動套用模板引擎。
Conf/config.php'HTML_FILE_SUFFIX' => '.html', // 靜態副檔名
'HTML_PATH' => './Html', // 生成目錄(需手動建立且可寫)
index.php 定義常數define('HTML_PATH', './Html');
class IndexAction extends Action {
public function index() {
// 參數:靜態檔名、靜態路徑、模板檔、編碼、Content-Type
$this->buildHtml('index', HTML_PATH . '/', 'Index:index', 'utf-8');
$this->display(); // 同時正常顯示動態頁
}
}
| 參數 | 說明 |
|---|---|
| $htmlFile | 生成檔名(不含副檔名),如 'list/2024/05' 會生成 list/2024/05.html |
| $htmlPath | 生成目錄,預設 HTML_PATH 常數 |
| $templateFile | 模板規格:'模組:操作',空值為當前操作模板 |
| $charset | 編碼,**需寫 'utf-8' 不要寫 'utf-8' |
| $contentType | 預設 'text/html' |
靜態化非銀彈,動態互動(評論、購物車、個性化推薦)仍需 AJAX 或 Edge Side Includes (ESI) 解決。