首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 文字檔自動發布新聞系統:資料庫替代方案

     編輯:PHP 相關知識

輕量級新聞發布:純文字檔 + 目錄掃描 + 靜態頁生成

無資料庫環境下,以文字檔儲存新聞內容,利用檔案系統時間排序、模板引擎生成靜態頁,構建簡易發布系統。

系統架構


news/ 目錄結構:
news/
├── 20240115_new-year.txt
├── 20240120_spring-festival.txt
└── ...

檔案格式 (第一行標題,其餘正文):
新年快樂!全站更新公告
內容第一段...
內容第二段...

核心程式碼

1. 新聞列表顯示 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>";
?>

2. 新聞內容頁 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>

3. 前台嵌入列表

<?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 解析

遷移至資料庫的考量點

  1. 並發寫入:檔案鎖 (flock) 效能差,資料庫行級鎖優越。
  2. 查詢靈活性:SQL 支援複雜篩選、排序、聚合、JOIN。
  3. 關聯資料:作者、分類、標籤、評論等關聯實體。
  4. 備份/復原:資料庫單一檔案/匯出檔 vs 大量分散文字檔。
  5. 擴展性:讀寫分離、分片、叢集部署。

現代化替代:靜態站點生成器

  • Hugo:Go 語言、極快、Markdown 內容、模板功能強。
  • Jekyll:Ruby、GitHub Pages 原生支援。
  • Astro / Next.js (SSG):React/Vue/Svelte 元件、TypeScript、現代前端工具鏈。

文字檔新聞系統適合極簡部署、無資料庫、低併發場景。理解其運作機制有助於掌握靜態生成核心邏輯,但業務增長時請果斷遷移至資料庫或 SSG。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved