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

PHP 批量生成靜態 HTML/TXT 檔案:模板替換、資料庫查詢、檔案寫入完整流程

     編輯:PHP 綜合知識

靜態化是高流量網站常用優化手段:將動態頁面預先生成靜態 HTML/TXT,減輕資料庫與 PHP 處理壓力。本文提供完整批量生成腳本,涵蓋資料庫連線、模板讀取、佔位符替換、檔案寫入與資源釋放。

1. 資料庫連線設定 conn.php

<?php
// conn.php
$host   = '127.0.0.1';
$user   = 'db_user';
$pass   = 'db_pass';
$dbname = 'my_database';
$charset = 'utf8mb4';

$mysqli = new mysqli($host, $user, $pass, $dbname);
if ($mysqli->connect_errno) {
    die("Connect failed: " . $mysqli->connect_error);
}
$mysqli->set_charset($charset);
// 供其他腳本 require 後直接使用 $mysqli

2. HTML 模板檔案 template.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{title}</title>
</head>
<body>
    <h1>{title}</h1>
    <div class="content">{content}</div>
    <p class="meta">發布時間:{pub_time}</p>
</body>
</html>

3. 批量生成 HTML 腳本 gen_html.php

<?php
require_once 'conn.php';

$outputDir = __DIR__ . '/html';
if (!is_dir($outputDir)) mkdir($outputDir, 0755, true);

// 讀取模板一次
$template = file_get_contents(__DIR__ . '/template.html');
if ($template === false) die('模板讀取失敗');

// 查詢需生成的文章
$sql = "SELECT id, title, content, created_at FROM articles WHERE status = 1";
$res = $mysqli->query($sql);
if (!$res) die("Query failed: " . $mysqli->error);

$success = $fail = 0;
while ($row = $res->fetch_assoc()) {
    $id = (int)$row['id'];
    $file = $outputDir . "/{$id}.html";

    // 替換佔位符
    $html = str_replace(
        ['{title}', '{content}', '{pub_time}'],
        [$row['title'], $row['content'], $row['created_at']],
        $template
    );

    // 寫入檔案 (LOCK_EX 避免並發衝突)
    if (file_put_contents($file, $html, LOCK_EX) !== false) {
        $success++;
    } else {
        $fail++;
        error_log("生成失敗: $file");
    }
}

$res->free();
$mysqli->close();

echo "完成:成功 $success,失敗 $fail\n";

4. 批量生成 TXT 純文字版 gen_txt.php

<?php
require_once 'conn.php';

$outputDir = __DIR__ . '/txt';
if (!is_dir($outputDir)) mkdir($outputDir, 0755, true);

$sql = "SELECT id, title, content FROM articles WHERE status = 1";
$res = $mysqli->query($sql);

while ($row = $res->fetch_assoc()) {
    $id = (int)$row['id'];
    $file = $outputDir . "/{$id}.txt";

    // 簡單格式:標題 + 換行 + 內容 (去除 HTML 標籤)
    $text = $row['title'] . "\n\n" . strip_tags($row['content']);

    file_put_contents($file, $text, LOCK_EX);
}

$res->free();
$mysqli->close();
echo "TXT 生成完成\n";

5. 進階優化與擴充

需求方案關鍵點
大量資料 (10萬+) 避免記憶體爆炸使用 mysqli::use_result() 或 PDO fetch() 游標模式不一次性載入所有行,逐行處理
模板邏輯複雜 (判斷、迴圈、繼承)引入模板引擎:Twig, Blade, Smarty編譯快取、語法豐富、安全過濾
生成後自動部署到 CDN/靜態伺服器腳本結束後呼叫 rsync、aws s3 sync、FTP 上傳結合 CI/CD 流程
增量生成 (只更新變更文章)資料表加 updated_at、last_generated_at,查詢時過濾避免全量重建浪費 IO
多進程並行加速pcntl_fork 或 GuzzleHttp\Pool 非同步併發Windows 用 popen 啟動多個 CLI 進程
URL 重寫對應生成時同步產出 Nginx rewrite map 或資料庫路由表前端訪問 /article/123 映射到 /html/123.html

6. 定時自動化 (Crontab / Windows Task Scheduler)

> /var/log/gen_html.log 2>&1

# Windows 任務排程器
# 程式: C:\php82\php.exe
# 參數: C:\www\scripts\gen_html.php
# 觸發: 每日/每小時

7. 安全與健壯性提醒

  • 輸出目錄權限:Web 伺服器需讀取權限,但**不可**有執行權限 (防止上傳木馬被執行)。
  • 檔名安全:使用資料庫 ID 或 md5($title . $id),避免使用者控制的標題直接做檔名 (路徑遍歷風險)。
  • 模板注入:若模板內容來自使用者輸入,嚴禁直接 str_replace,必須用沙箱模板引擎 (Twig Sandbox)。
  • 磁碟空間監控:生成前檢查 disk_free_space(),空間不足報警停止。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved