首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 使用 Smarty 產生靜態 HTML 檔案完整範例

     編輯:PHP 綜合知識

核心概念

Smarty fetch() 回傳渲染後的 HTML 字串,配合 file_put_contents() 寫入檔案,即可實現靜態化。

首頁靜態化範例

function buildIndexHtml() {
    global $smarty, $articleModel;

    // 1. 準備資料
    $news = $articleModel->getLatest(6);
    foreach ($news as &$n) {
        $n['short_title'] = mb_strimwidth($n['title'], 0, 36, '…');
    }
    $smarty->assign('newslist', $news);

    // 2. 取得渲染結果
    $html = $smarty->fetch('index.tpl'); // 不輸出,回傳字串

    // 3. 寫入檔案
    $file = ROOT_PATH . 'index.html';
    @file_put_contents($file, $html);

    return true;
}

分類頁面批次靜態化

function buildCategoryPages() {
    global $smarty, $catModel;
    $categories = $catModel->getAll();

    foreach ($categories as $cat) {
        $articles = $articleModel->getByCat($cat['id'], 20);
        $smarty->assign('articles', $articles);
        $smarty->assign('cat', $cat);

        $html = $smarty->fetch('category.tpl');
        $dir = ROOT_PATH . 'category/' . $cat['id'] . '/';
        if (!is_dir($dir)) mkdir($dir, 0755, true);
        @file_put_contents($dir . 'index.html', $html);
    }
}

文章詳情頁靜態化

function buildArticleHtml($id) {
    global $smarty, $articleModel;
    $article = $articleModel->get($id);
    if (!$article) return false;

    $smarty->assign('article', $article);
    $html = $smarty->fetch('article.tpl');

    $dir = ROOT_PATH . 'article/' . ceil($id / 1000) . '/'; // 分目錄避免單目錄檔案過多
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    @file_put_contents($dir . $id . '.html', $html);
    return true;
}

觸發機制

  • 後台發布/編輯/刪除 時呼叫對應靜態化函式。
  • 定時任務 每小時重建首頁、分類頁。
  • 手動觸發 後台提供「重新生成靜態頁」按鈕。

進階優化

  • 使用 ob_start() / ob_get_clean() 捕獲輸出,支援非 Smarty 模板。
  • CDN 刷新 API 配合靜態化自動預熱。
  • Nginx try_files 先嘗試靜態檔,不存在再落回 PHP 動態渲染:
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

注意事項

  • 靜態化頁面不包含動態資訊 (購物車數量、用戶狀態),需用 AJAX 區塊載入或 ESI。
  • 大量檔案寫入注意磁碟 I/O、inode 限制,適當分目錄。
  • 部署多台 Web 服務器時,靜態檔需共享儲存 (NFS、GlusterFS) 或同步機制 (rsync、lsyncd)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved