萬盛學電腦網

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

PHP 結合 Smarty 產生靜態頁面:首頁、列表頁、內容頁批次靜態化範例

利用 Smarty 內建 fetch() 取得渲染後 HTML,寫入靜態檔案,實現人工觸發的靜態化發布流程,避免每次請求都執行 PHP。

核心靜態化函數

<?php
// 靜態化首頁
function staticIndex() {
    global $smarty, $article;
    $newslist = $article->getArticles(null, 54, 'DESC', 1, 6, false, 1, 2, '', 0, 0, 1);
    if ($newslist) {
        foreach ($newslist as $k => $v) {
            $newslist[$k]['title_all'] = $v['title'];
            $newslist[$k]['title'] = cutstr($v['title'], 36, '...');
        }
        $smarty->assign('newslist', $newslist);
    }
    $content = $smarty->fetch('index.html', true); // true = 返回字串而非輸出
    $staticFile = ROOT_PATH . 'index.html';
    file_put_contents($staticFile, $content);
    return true;
}

// 靜態化列表頁(按分類)
function staticContent() {
    global $smarty;
    $ids = $this->getListIds(); // 取得所有內容 ID 與分類
    foreach ($ids as $row) {
        $catDir = ROOT_PATH . 'demo/' . $row['catid'];
        if (!is_dir($catDir)) mkdir($catDir, 0755, true);
        $html = $this->getDemoContent($row['demoid']);
        $file = $catDir . '/' . $row['demoid'] . '.html';
        file_put_contents($file, $html);
    }
    return true;
}

// 取得單頁渲染內容
function getDemoContent($id) {
    global $smarty, $view_templates;
    $smarty->template_dir = ROOT_PATH . $view_templates;
    $detail = $this->getMobanDetail($id);
    $moban = (new demo())->MobanList($id);
    foreach ($moban as $k => $v) $smarty->assign($k, $v);
    $smarty->assign('pre_title', $moban['membername']);
    $smarty->assign('mobandetail', $moban);
    return $smarty->fetch('demo_show.html', true);
}
?>

關鍵點

  • $smarty->fetch('tpl', true) 回傳渲染結果字串,不直接輸出。
  • file_put_contents() 簡化檔案寫入(PHP 5+)。
  • 目錄不存在時 mkdir(..., true) 遞迴建立。
  • 人工觸發(後台按鈕呼叫),靈活控制發布時機。
copyright © 萬盛學電腦網 all rights reserved