核心思路:模板檔案 + 動態資料 = 靜態 HTML。模板中預留佔位符 (如 {title}、{content}),執行時讀取模板、替換佔位符、寫入靜態檔案。
$rs = [
'title' => '文章標題',
'content' => '文章內容...',
'description' => 'SEO 描述',
'keywords' => '關鍵字,PHP,靜態化',
'z_a' => 'category',
'sysa' => 'system',
'filesendid' => 123,
];
$fileName = md5_filename($rs[0], $rs['z_a'], $rs['filesendid']);
$path = get_path($rs['sysa']) . $rs['z_a'] . '/';
$parent = $_SERVER['DOCUMENT_ROOT'];
$filePath = $parent . '\\' . $path; // Windows 路徑
$template = $fileContent; // 假設已讀取模板檔案
$replacements = [
'{path}' => path($rs['z_a'], $rs['sysa']),
'{htmlAbout}' => htmlAbout($rs['z_a'], 10, 8, 0, ''),
'{htmlTemplate}' => htmlTemplate(0),
'{htmlMenu}' => htmlMenu($rs['sysa']),
'{htmlHelp}' => htmlHelp($rs['sysa']),
'{htmlNews}' => htmlAbout($rs['z_a'], 0, 8, 0, ''),
'{htmlHot}' => htmlAbout($rs['z_a'], 0, 8, 1, ''),
'{htmlSoure}' => htmlTemplate(1),
'php簡單生成html靜態頁面代碼' => $rs['title'], // 注意:這行疑似模板中寫死的標題
'{htmlContent}' => $rs['content'],
'{description}' => $rs['description'],
'{keywords}' => $rs['keywords'],
];
$html = str_replace(array_keys($replacements), array_values($replacements), $template);
function makeHtml($content, $dir, $filename) {
// 確保目錄存在
if (!is_dir($dir)) {
mkdir($dir, 0755, true); // 遞迴建立
}
$fullPath = $dir . $filename;
// 使用 file_put_contents 簡化寫入 (PHP 5+)
$bytes = file_put_contents($fullPath, $content, LOCK_EX);
if ($bytes === false) {
throw new Exception("靜態檔案寫入失敗: $fullPath");
}
return $fullPath;
}
// 呼叫
makeHtml($html, $filePath, $fileName);
str_replace。ob_start() 包含模板檔,直接捕獲輸出。ID-slug.html 格式。777htmlspecialchars()$fileName 不含 ../