靜態頁面生成能大幅降低伺服器負載、提升 SEO 效果。本文示範最簡單的「模板 + 字串替換」法,適合中小型專案快速實作。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{page_title}</title>
</head>
<body>
<h1>{page_title}</h1>
<iframe width="100%" height="1000px" frameborder="0" src="{page_url}"></iframe>
</body>
</html>
<?php
header('Content-Type: text/html; charset=utf-8');
// 動態資料
$title = "PHP 動態生成靜態頁面範例";
$url = "https://www.example.com/";
$template_file = 'temp.html';
$output_file = 'page_' . date('Ymd_His') . '.html';
// 讀取模板
$content = file_get_contents($template_file);
if ($content === false) {
die('模板讀取失敗');
}
// 替換佔位符
$replacements = [
'{page_title}' => $title,
'{page_url}' => $url,
];
$content = str_replace(array_keys($replacements), array_values($replacements), $content);
// 寫入靜態檔案
if (file_put_contents($output_file, $content) === false) {
die('靜態檔案寫入失敗,請檢查目錄權限');
}
echo "<script>alert('生成成功: $output_file'); window.location.href='$output_file';</script>";
?>
<?php
class SimpleTemplate {
private $vars = [];
private $blocks = [];
public function assign($key, $value) {
$this->vars[$key] = $value;
}
public function assignBlock($blockName, array $items) {
$this->blocks[$blockName] = $items;
}
public function render($template) {
// 1. 簡單變數替換
$output = str_replace(
array_map(fn($k) => "{$k}", array_keys($this->vars)),
array_values($this->vars),
$template
);
// 2. 區塊迴圈處理 (簡易版:...)
foreach ($this->blocks as $blockName => $items) {
$pattern = "/(.*?)/s";
if (preg_match($pattern, $output, $matches)) {
$blockTpl = $matches[1];
$blockHtml = '';
foreach ($items as $item) {
$blockHtml .= str_replace(
array_map(fn($k) => "{$k}", array_keys($item)),
array_values($item),
$blockTpl
);
}
$output = str_replace($matches[0], $blockHtml, $output);
}
}
return $output;
}
}
// 使用範例
$tpl = new SimpleTemplate();
$tpl->assign('{site_name}', '我的網站');
$tpl->assignBlock('item', [
['{name}' => '商品A', '{price}' => 100],
['{name}' => '商品B', '{price}' => 200],
]);
$template = file_get_contents('template_with_loop.html');
echo $tpl->render($template);
?>
<ul>
<li>{name} - ${price}</li>
</ul>
flock() 防止檔案損毀