利用 PHP 將動態資料寫入靜態 HTML,是早期高流量站點常用的「偽靜態」架構。核心思想:**資料庫存內容 + 模板存結構 + PHP 做替換輸出靜態檔**。
CREATE TABLE news (
id INT AUTO_INCREMENT PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
path TEXT NOT NULL -- 靜態檔路徑,如 123.html
);
conn.php<?php
$pdo = new PDO('mysql:host=localhost;dbname=database;charset=utf8', 'user', 'pass');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
add.form.html<form method="post" action="add.php">
標題: <input type="text" name="title"><br>
內容: <textarea name="content"></textarea><br>
<input type="submit" value="發布">
</form>
model.htm<html><body>
<h1>{title}</h1>
<div>{content}</div>
</body></html>
用 {title}、{content} 等標記標示待替換位置。
add.php<?php
require_once 'conn.php';
$title = $_POST['title'] ?? '';
$content = $_POST['content'] ?? '';
// 簡易產生靜態檔名:自增計數器 (實務建議用 id 或 hash)
$countFile = 'count.txt';
$num = file_exists($countFile) ? (int)file_get_contents($countFile) : 0;
$num++;
file_put_contents($countFile, $num);
$path = $num . '.html';
// 寫入資料庫
$stmt = $pdo->prepare('INSERT INTO news (title, content, path) VALUES (?, ?, ?)');
$stmt->execute([$title, $content, $path]);
// 讀取模板、替換、寫入靜態檔
$template = file_get_contents('model.htm');
$html = str_replace(['{title}', '{content}'], [$title, $content], $template);
file_put_contents($path, $html);
echo "<a href='$path' target='_blank'>查看生成的靜態頁</a>";
{field}) 標示動態區塊。str_replace 陣列寫法一次替換多個標記,效能佳。id.html 或 md5(title).html 避免衝突。UPDATE 資料庫 + 重新生成靜態檔;刪除時 DELETE + unlink($path) 刪除實體檔。純靜態化已較少見,現代架構多採用:
fastcgi_cache / Varnish / Redis 全頁 HTML 快取。但理解「模板替換生成靜態檔」原理,有助於理解快取失效、CDN 刷新、邊緣渲染等現代概念的本質。