{title})替換動態資料| 函式 | 用途 | 常用模式 |
|---|---|---|
| fopen | 開啟檔案 | fopen($path, 'r'|'w'|'a') |
| fread | 讀取內容 | fread($fp, filesize($path)) |
| fwrite | 寫入內容 | fwrite($fp, $content) |
| fclose | 關閉檔案 | fclose($fp) |
| filesize | 取得檔案大小 | filesize($path) |
| unlink | 刪除檔案 | unlink($path) |
| mkdir | 建立目錄 | mkdir($path, 0755, true) |
<?php
// 1. 讀取模板
$fp = fopen('template.htm', 'r');
$template = fread($fp, filesize('template.htm'));
fclose($fp);
// 2. 替換標記
$data = [
'{title}' => '最新消息',
'{content}' => '這裡是動態生成的內容...',
];
$html = str_replace(array_keys($data), array_values($data), $template);
// 3. 寫入靜態檔
$file = 'news_' . date('YmdHis') . '.html';
$fp = fopen($file, 'w');
fwrite($fp, $html);
fclose($fp);
echo "生成成功:{$file}";
?>
<?php
class HtmlGenerator {
private $dir, $name, $path, $handle;
public function __construct($dir = './', $name = '') {
$this->dir = rtrim($dir, '/') . '/';
$this->name = $name ?: basename(__FILE__, '.php') . '.html';
$this->path = $this->dir . $this->name;
if (!is_dir($this->dir)) mkdir($this->dir, 0755, true);
ob_start(); // 開啟輸出緩衝
}
public function __destruct() {
ob_end_clean();
}
public function save() {
$content = ob_get_contents();
if (file_exists($this->path)) @unlink($this->path);
$this->handle = fopen($this->path, 'w');
if (!is_writable($this->path) || !fwrite($this->handle, $content)) {
fclose($this->handle);
return false;
}
fclose($this->handle);
return $this->path;
}
}
// 使用方式
$html = new HtmlGenerator('./cache/', 'article_123.html');
// ... 在此輸出頁面內容(echo、include view 等) ...
$path = $html->save();
echo "靜態頁已生成:{$path}";
?>
搭配 ob_start() / ob_get_contents() / ob_end_clean(),可直接捕獲 PHP 輸出的 HTML,無需手動拼接字串。
<?php
ob_start();
include 'view/article_view.php'; // 該檔案輸出完整 HTML
$content = ob_get_clean(); // 取得內容並關閉緩衝
file_put_contents('static/article.html', $content); // PHP 5.4+ 簡寫
?>
flock)避免衝突。靜態化是提升 PHP 應用效能的經典手段,配合 CDN 更能發揮極致效能。