核心流程:讀取模板 → 替換佔位符 → 寫入靜態檔案。適用於內容更新頻率低、流量大、SEO 敏感的頁面 (文章詳情、商品頁、列表頁)。
| 函數 | 用途 | 範例 |
|---|---|---|
fopen($path, $mode) | 開啟檔案 | $fp = fopen('tpl.htm', 'r'); |
fread($fp, $length) | 讀取內容 | $str = fread($fp, filesize('tpl.htm')); |
filesize($path) | 取得檔案大小 | 配合 fread 讀取完整檔案 |
fwrite($fp, $string) | 寫入內容 | fwrite($handle, $html); |
fclose($fp) | 關閉檔案 | 釋放鎖定、緩衝區刷新 |
unlink($path) | 刪除檔案 | 更新時先刪舊檔 |
mkdir($path, 0755, true) | 建立目錄 (遞迴) | 確保輸出目錄存在 |
<?php
// 1. 讀取模板
$fp = fopen('template.htm', 'r');
$template = fread($fp, filesize('template.htm'));
fclose($fp);
// 2. 替換佔位符 {title}、{content}
$title = '最新文章標題';
$content = '文章詳細內容...';
$template = str_replace('{title}', $title, $template);
$template = str_replace('{content}', $content, $template);
// 3. 寫入靜態檔
$id = 'article_123';
$path = 'html/' . $id . '.html';
$handle = fopen($path, 'w');
fwrite($handle, $template);
fclose($handle);
echo "靜態頁生成成功:$path";
<?php
/**
* 靜態 HTML 生成類
* 支援多模板、輸出目錄配置、緩衝區輸出捕獲
*/
class HtmlGenerator {
private $tpl_dir = 'templates/';
private $out_dir = 'html/';
private $tpl_ext = '.htm';
private $out_ext = '.html';
public function __construct($tpl_dir = '', $out_dir = '') {
if ($tpl_dir) $this->tpl_dir = rtrim($tpl_dir, '/') . '/';
if ($out_dir) $this->out_dir = rtrim($out_dir, '/') . '/';
// 確保輸出目錄存在
if (!is_dir($this->out_dir)) mkdir($this->out_dir, 0755, true);
}
/**
* 根據模板與資料生成靜態檔
* @param string $tpl_name 模板名稱 (不含副檔名)
* @param array $data 替換資料 ['{key}' => 'value']
* @param string $out_name 輸出檔名 (不含副檔名),預設同模板名
* @return bool|string 成功回傳輸出路徑,失敗回傳 false
*/
public function generate($tpl_name, array $data, $out_name = '') {
$tpl_path = $this->tpl_dir . $tpl_name . $this->tpl_ext;
if (!is_readable($tpl_path)) return false;
$out_name = $out_name ?: $tpl_name;
$out_path = $this->out_dir . $out_name . $this->out_ext;
// 讀取模板
$content = file_get_contents($tpl_path);
// 批次替換
foreach ($data as $placeholder => $value) {
$content = str_replace($placeholder, $value, $content);
}
// 寫入檔案 (原子寫入:先寫暫存檔再 rename)
$tmp_path = $out_path . '.tmp';
if (file_put_contents($tmp_path, $content) === false) return false;
if (!rename($tmp_path, $out_path)) {
@unlink($tmp_path);
return false;
}
@chmod($out_path, 0644);
return $out_path;
}
/**
* 捕獲 PHP 輸出緩衝區並生成靜態頁 (適合複雜邏輯頁面)
*/
public function generateFromOutput($tpl_name, callable $logic, $out_name = '') {
ob_start();
try {
$logic(); // 執行業務邏輸出 HTML
$content = ob_get_clean();
} catch (Exception $e) {
ob_end_clean();
return false;
}
// 同樣寫入流程...
$out_name = $out_name ?: $tpl_name;
$out_path = $this->out_dir . $out_name . $this->out_ext;
$tmp_path = $out_path . '.tmp';
if (file_put_contents($tmp_path, $content) === false) return false;
return rename($tmp_path, $out_path) ? $out_path : false;
}
public function delete($file_name) {
$path = $this->out_dir . $file_name . $this->out_ext;
return is_file($path) && unlink($path);
}
}
// 使用範例
$gen = new HtmlGenerator('tpl/', 'public/html/');
$gen->generate('article', [
'{title}' => 'PHP 靜態化實戰',
'{content}' => '<p>內容...</p>',
'{time}' => date('Y-m-d H:i:s')
], 'article_1001');
{variable}、{$variable}、{{ variable }} (Twig 風格)。{block name}{/block},實現版面複用。try_files $uri $uri/ /index.php,PHP 完全不參與靜態頁請求。靜態化是高流量 PHP 站點效能倍增器,配合現代模板引擎與異步隊列,可支撐百萬級日 PV。