透過預先設計含佔位符的 HTML 模板,使用 str_replace 將標籤替換為動態資料,快速生成靜態頁面,降低資料庫查詢壓力。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{site_title} - 範例網站</title>
</head>
<body>
<h1>{site_title}</h1>
<iframe src="{site_url}" width="100%" height="800"></iframe>
</body>
</html>
<?php
header('Content-Type: text/html; charset=utf-8');
$title = "PHP 動態生成靜態頁面範例";
$url = "https://example.com";
$templateFile = 'template.html';
$outputFile = 'static_page.html';
$fp = fopen($templateFile, 'r');
$content = fread($fp, filesize($templateFile));
fclose($fp);
// 替換標籤
$content = str_replace('{site_title}', $title, $content);
$content = str_replace('{site_url}', $url, $content);
$handle = fopen($outputFile, 'w');
fwrite($handle, $content);
fclose($handle);
echo "<script>alert('生成成功'); location.href='$outputFile';</script>";
?>
<?php
function renderTemplate($tpl, $data) {
// 簡易區塊替換 {block:items}...{/block}
if (preg_match('/\{block:(\w+)\}(.*?)\{\/block:\1\}/s', $tpl, $m)) {
$blockName = $m[1];
$blockTpl = $m[2];
$items = $data[$blockName] ?? [];
$rendered = '';
foreach ($items as $item) {
$itemHtml = $blockTpl;
foreach ($item as $k => $v) {
$itemHtml = str_replace("{$blockName}.$k", $v, $itemHtml);
}
$rendered .= $itemHtml;
}
$tpl = str_replace($m[0], $rendered, $tpl);
}
// 單一變數替換
foreach ($data as $k => $v) {
if (!is_array($v)) {
$tpl = str_replace("{$k}", $v, $tpl);
}
}
return $tpl;
}
// 使用範例
$template = file_get_contents('list_tpl.html');
$data = [
'page_title' => '商品列表',
'items' => [
['items.name'=>'商品A', 'items.price'=>100],
['items.name'=>'商品B', 'items.price'=>200],
]
];
echo renderTemplate($template, $data);
?>
| 優點 | 缺點 |
|---|---|
| 零依賴、效能極佳 | 邏輯複雜時模板難以維護 |
| 易於理解與除錯 | 缺乏模板繼承、區塊覆蓋等進階功能 |
| 生成純靜態 HTML,適合 CDN 快取 | 大量資料替換記憶體佔用高 |
ob_start() 捕獲輸出,避免直接輸出