動態頁面:請求 → Web 服務器調用 PHP 腳本 → PHP 解析器解析 → 連接數據庫讀寫 → 生成 HTML → 返回瀏覽器。優點:實時性強;缺點:服務器壓力大,響應慢。
靜態頁面:請求 → Web 服務器直接讀取 HTML 文件 → 返回瀏覽器。優點:無解析開銷,無數據庫交互,極快,承載能力強;缺點:內容固化,需重新生成才能更新。
模板即含佔位符的 HTML 文件(如 {title}、{content})。PHP 讀取模板,替換佔位符為實際數據,最後將結果寫入 .html 文件而非直接輸出。核心函數:fopen()、fwrite()、fclose()。
<?php
$title = "拓邁國際測試模板";
$file = "TwoMax Inter test templet
author: Matrix@Two_Max";
$fp = fopen("temp.html", "r");
$content = fread($fp, filesize("temp.html"));
fclose($fp);
$content = str_replace("{title}", $title, $content);
$content = str_replace("{file}", $file, $content);
$filename = "test/test.html";
$handle = fopen($filename, "w");
if (!is_writable($filename)) die("文件不可寫,請檢查權限!");
if (!fwrite($handle, $content)) die("生成失敗!");
fclose($handle);
die("創建文件 $filename 成功!");
?>
在模板放置 {articletable},PHP 循環拼接列表 HTML 後一次性替換:
$list = '';
$sql = "SELECT id, title, filename FROM article";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$list .= "<a href='{$row['filename']}'>{$row['title']}</a><br>";
}
$content = str_replace("{articletable}", $list, $content);
查詢總記錄數計算總頁數,for 循環逐頁生成:
$onepage = 20;
$sql = "SELECT id FROM article WHERE channel='$channelid'";
$num = mysql_num_rows(mysql_query($sql));
$allpages = ceil($num / $onepage);
for ($i = 0; $i < $allpages; $i++) {
$indexpath = ($i == 0) ? "index.html" : "index_$i.html";
$start = $i * $onepage;
$list = '';
$pageSql = "SELECT title, filename FROM article WHERE channel='$channelid' LIMIT $start, $onepage";
$pageQuery = mysql_query($pageSql);
while ($row = mysql_fetch_array($pageQuery)) {
$list .= "<a href='{$row['filename']}'>{$row['title']}</a><br>";
}
$pageContent = str_replace("{articletable}", $list, $content);
if (is_file($indexpath)) @unlink($indexpath); // 覆蓋舊文件
$handle = fopen($indexpath, "w");
fwrite($handle, $pageContent);
fclose($handle);
}
echo "共生成 $allpages 個靜態頁面!";
0777(Linux)確保可寫。mysql_* 函數,實際項目請升級至 mysqli/PDO 並防注入。