萬盛學電腦網

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

PHP 靜態頁面生成技術:模板替換與檔案操作實戰

靜態頁生成核心流程

  1. 讀取 HTML 模板檔
  2. 以標記(如 {title})替換動態資料
  3. 將結果寫入 .html 靜態檔

核心檔案函式速查

函式用途常用模式
fopen開啟檔案fopen($path, 'r'|'w'|'a')
fread讀取內容fread($fp, filesize($path))
fwrite寫入內容fwrite($fp, $content)
fclose關閉檔案fclose($fp)
filesize取得檔案大小filesize($path)
unlink刪除檔案unlink($path)
mkdir建立目錄mkdir($path, 0755, true)

基礎範例:模板替換生成靜態頁

<?php
// 1. 讀取模板
$fp = fopen('template.htm', 'r');
$template = fread($fp, filesize('template.htm'));
fclose($fp);

// 2. 替換標記
$data = [
    '{title}'   => '最新消息',
    '{content}' => '這裡是動態生成的內容...',
];
$html = str_replace(array_keys($data), array_values($data), $template);

// 3. 寫入靜態檔
$file = 'news_' . date('YmdHis') . '.html';
$fp = fopen($file, 'w');
fwrite($fp, $html);
fclose($fp);

echo "生成成功:{$file}";
?>

進階封裝:靜態頁生成類別

<?php
class HtmlGenerator {
    private $dir, $name, $path, $handle;

    public function __construct($dir = './', $name = '') {
        $this->dir = rtrim($dir, '/') . '/';
        $this->name = $name ?: basename(__FILE__, '.php') . '.html';
        $this->path = $this->dir . $this->name;

        if (!is_dir($this->dir)) mkdir($this->dir, 0755, true);
        ob_start(); // 開啟輸出緩衝
    }

    public function __destruct() {
        ob_end_clean();
    }

    public function save() {
        $content = ob_get_contents();
        if (file_exists($this->path)) @unlink($this->path);

        $this->handle = fopen($this->path, 'w');
        if (!is_writable($this->path) || !fwrite($this->handle, $content)) {
            fclose($this->handle);
            return false;
        }
        fclose($this->handle);
        return $this->path;
    }
}

// 使用方式
$html = new HtmlGenerator('./cache/', 'article_123.html');
// ... 在此輸出頁面內容(echo、include view 等) ...
$path = $html->save();
echo "靜態頁已生成:{$path}";
?>

輸出緩衝(Output Buffering)技巧

搭配 ob_start() / ob_get_contents() / ob_end_clean(),可直接捕獲 PHP 輸出的 HTML,無需手動拼接字串。

<?php
ob_start();
include 'view/article_view.php'; // 該檔案輸出完整 HTML
$content = ob_get_clean(); // 取得內容並關閉緩衝

file_put_contents('static/article.html', $content); // PHP 5.4+ 簡寫
?>

應用場景與注意事項

  • ✅ 適合:內容較固定、流量大、SEO 重視的頁面(文章、商品頁、分類頁)。
  • ✅ 更新策略:發布/編輯內容時重新生成;或定時任務批次更新。
  • ⚠️ 避免:高度個人化、即時互動、頻繁變動的頁面。
  • ⚠️ 權限:確保目標目錄可寫,生成後建議設為唯讀。
  • ⚠️ 並發:高併發生成時加檔案鎖(flock)避免衝突。

靜態化是提升 PHP 應用效能的經典手段,配合 CDN 更能發揮極致效能。

copyright © 萬盛學電腦網 all rights reserved