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

PHP 批量生成靜態 HTML/TXT 檔案實作:模板替換與資料庫驅動

     編輯:PHP 相關知識

將動態頁面靜態化可大幅降低資料庫壓力、提升前端效能並利於 SEO。本文示範從 MySQL 讀取資料,套用 HTML 模板替換佔位符,批量生成 .html 或 .txt 靜態檔案的完整流程。

一、資料庫連線 conn.php

<?php
// 建議改用 PDO 或 mysqli,此處沿用舊 mysql_* 示範邏輯
$link = mysqli_connect("localhost", "db_user", "db_pass", "my_database");
if (!$link) die("Connect failed: " . mysqli_connect_error());
mysqli_set_charset($link, "utf8");
?>

二、HTML 模板檔 template.html

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{title}</title>
</head>
<body>
{introduce}
</body>
</html>

佔位符採用 {欄位名} 格式,易於 str_replace 處理。

三、批量生成 HTML 程式 generate_html.php

<?php
require_once("conn.php");

$query = "SELECT id, title, introduce FROM my_table";
$result = mysqli_query($link, $query);
if (!$result) die("Query failed: " . mysqli_error($link));

$template = file_get_contents("template.html");
if ($template === false) die("Template file not found");

$output_dir = "html/";
if (!is_dir($output_dir)) mkdir($output_dir, 0755, true);

while ($row = mysqli_fetch_assoc($result)) {
    $id = $row['id'];
    $title = $row['title'];
    $introduce = $row['introduce'];

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

    $path = $output_dir . $id . ".html";
    if (file_put_contents($path, $html) === false) {
        error_log("Failed to write $path");
    } else {
        echo "生成成功: $path
"; } } mysqli_free_result($result); mysqli_close($link); ?>

四、批量生成 TXT 程式 generate_txt.php

<?php
require_once("conn.php");

$query = "SELECT id, title, introduce FROM pro_courses";
$result = mysqli_query($link, $query);

$output_dir = "txt/";
if (!is_dir($output_dir)) mkdir($output_dir, 0755, true);

while ($row = mysqli_fetch_assoc($result)) {
    $id = $row['id'];
    $content = strip_tags($row['introduce']); // 移除 HTML 標籤
    $path = $output_dir . $id . ".txt";
    file_put_contents($path, $content);
}

mysqli_free_result($result);
mysqli_close($link);
?>

五、進階優化與生產級建議

1. 使用輸出緩衝區減少 I/O

// 大量檔案時,累積內容批次寫入或使用 fwrite 追加
$fp = fopen($path, 'w');
fwrite($fp, $html);
fclose($fp);

2. 模板引擎替換(支援迴圈、條件、繼承)

<?php
// 使用 Smarty / Blade / Twig
$smarty->assign('row', $row);
$html = $smarty->fetch('template.tpl');
file_put_contents($path, $html);

3. 佇列非同步生成(避免阻塞請求)

  • 請求寫入 Redis/RabbitMQ 佇列:{id: 123, action: 'generate_html'}
  • Worker 進程消費佇列執行生成邏輯。
  • 前端輪詢或 WebSocket 通知完成。

4. 靜態檔案版本控制與部署

  • 生成至 /var/www/html/static/v20240115/ 版本目錄。
  • Nginx root 指向最新版本,或使用符號連結切換。
  • CDN 刷新快取 API 自動觸發。

5. 斷點續傳與錯誤重試

$status_file = "generate_status.json";
$status = file_exists($status_file) ? json_decode(file_get_contents($status_file), true) : [];
$last_id = $status['last_id'] ?? 0;

$query = "SELECT ... WHERE id > $last_id ORDER BY id LIMIT 1000";
// ... 生成 ...
$status['last_id'] = $current_id;
file_put_contents($status_file, json_encode($status));

六、Nginx 靜態檔案服務配置

server {
    listen 80;
    server_name static.example.com;
    root /var/www/html/static/current;

    location / {
        try_files $uri $uri/ =404;
        expires 30d;
        add_header Cache-Control "public";
    }

    # 防止 PHP 檔案被執行
    location ~ \.php$ {
        deny all;
    }
}

七、常見問題排查

問題原因解決
生成檔案為空/亂碼模板讀取失敗、編碼不一致確認 template.html 為 UTF-8 無 BOM、file_get_contents 正常
權限拒絕目錄擁有者非 PHP 執行用戶chown www-data:www-data html/、chmod 755
大量資料記憶體耗盡一次撈取過多行、模板過大分批處理 LIMIT、使用生成器 yield
佔位符未替換欄位名拼寫錯誤、模板佔位符格式不符統一佔位符命名規範、加入缺失欄位預設值
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved