萬盛學電腦網

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

PHP 生成靜態 HTML 檔案:模板替換、檔案操作與類封裝實戰

靜態化生成原理

核心流程:讀取模板 → 替換佔位符 → 寫入靜態檔案。適用於內容更新頻率低、流量大、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 風格)。
  • 支援條件/迴圈:建議直接引入 Twig 或 Blade 引擎,而非自造輪子。
  • 區塊繼承:{block name}{/block},實現版面複用。

部署架構建議

  1. 生成觸發:後台發布/編輯內容時 → 異步隊列 (Redis/RabbitMQ) → Worker 生成靜態頁。
  2. Web 伺服器直接服務靜態檔:Nginx try_files $uri $uri/ /index.php,PHP 完全不參與靜態頁請求。
  3. CDN 加速:靜態頁推送至 CDN 邊緣節點,極致效能。
  4. 增量更新:僅重新生成變更頁面及相關列表/索引頁。

靜態化是高流量 PHP 站點效能倍增器,配合現代模板引擎與異步隊列,可支撐百萬級日 PV。

copyright © 萬盛學電腦網 all rights reserved