無資料庫環境下,以文字檔儲存新聞內容,利用檔案系統時間排序、模板引擎生成靜態頁,構建簡易發布系統。
news/ 目錄結構:
news/
├── 20240115_new-year.txt
├── 20240120_spring-festival.txt
└── ...
檔案格式 (第一行標題,其餘正文):
新年快樂!全站更新公告
內容第一段...
內容第二段...
shownews.php<?php
// shownews.php
$newsPath = __DIR__ . '/news/';
$files = [];
$dir = new DirectoryIterator($newsPath);
foreach ($dir as $file) {
if ($file->isDot() || !$file->isFile()) continue;
if (pathinfo($file->getFilename(), PATHINFO_EXTENSION) !== 'txt') continue;
$files[$file->getFilename()] = $file->getMTime(); // 檔案修改時間
}
arsort($files); // 新est first
echo "<table>";
foreach ($files as $filename => $mtime) {
$content = file($newsPath . $filename);
$title = htmlspecialchars(trim($content[0]));
$id = basename($filename, '.txt');
$dateStr = date('Y年m月d日 H:i:s', $mtime);
echo "<tr><td><a href='pubnews.php?id=$id' target='_blank'>$title</a> ($dateStr)</td></tr>";
}
echo "</table>";
?>
pubnews.php<?php
// pubnews.php
$id = $_GET['id'] ?? '';
if (!$id) { header('Location: shownews.php'); exit; }
$filename = __DIR__ . "/news/$id.txt";
if (!is_file($filename)) { http_response_code(404); exit('新聞不存在'); }
$lines = file($filename);
$title = htmlspecialchars(trim($lines[0]));
$bodyLines = array_slice($lines, 1);
?>
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<title><?php echo $title; ?> - 新聞系統</title>
</head><body>
<blockquote>
<h2><?php echo $title; ?></h2>
<p><?php
foreach ($bodyLines as $line) {
echo nl2br(htmlspecialchars(trim($line))) . "\n";
}
?></p>
</blockquote>
</body></html>
<?php require 'shownews.php'; ?>
| 功能 | 實作方式 |
|---|---|
| 分頁 | array_slice($files, $offset, $limit) 配合 $_GET['page'] |
| 分類 | 子目錄 news/sports/, news/tech/,掃描時保留相對路徑 |
| 後台管理 | 表單上傳/編輯文字檔,驗證權限、CSRF Token |
| 搜尋 | 建立倒排索引 (SQLite FTS5 / Meilisearch) 或簡易 grep 掃描 |
| RSS/Atom | 遍歷檔案生成 XML,header('Content-Type: application/xml') |
| 標籤 | 檔名含標籤 20240115_[php,laravel]_news.txt 解析 |
flock) 效能差,資料庫行級鎖優越。文字檔新聞系統適合極簡部署、無資料庫、低併發場景。理解其運作機制有助於掌握靜態生成核心邏輯,但業務增長時請果斷遷移至資料庫或 SSG。