萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 動態生成靜態 HTML 頁面範例 (模板替換法)

靜態頁面生成能大幅降低伺服器負載、提升 SEO 效果。本文示範最簡單的「模板 + 字串替換」法,適合中小型專案快速實作。

模板檔案 (temp.html)

<!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>

生成腳本 (generate.php)

<?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);
?>

模板檔案範例 (template_with_loop.html)

<ul>

    <li>{name} - ${price}</li>

</ul>

生產環境建議

  • 成熟模板引擎:Smarty、Twig、Blade (Laravel)、Lathe - 支援繼承、過濾器、快取、沙箱
  • 快取機制:生成後設定過期時間,避免重複生成
  • 檔案鎖:併發生成時使用 flock() 防止檔案損毀
  • CDN 整合:生成後自動推送至 CDN 或靜態資源伺服器
  • 增量更新:僅重新生成資料異動相關頁面
copyright © 萬盛學電腦網 all rights reserved