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

PHP 文字檔即時新聞發布系統 (依檔案時間自動排序)

     編輯:PHP 綜合知識

需求

  • 新聞以純文字檔儲存於指定目錄。
  • 2. 檔名任意,以**檔案修改時間 (mtime)** 決定顯示順序 (最新在前)。 3. 文字檔支援簡易連結語法:${https://url} 或 ${https://url|顯示文字}。 4. 自動轉義 HTML 特殊字元,防 XSS。

完整程式碼 (news.php)

<?php
// 設定新聞目錄 (建議放在網站根目錄外)
define('NEWS_DIR', __DIR__ . '/../data/news/');

function renderNews(): string
{
    if (!is_dir(NEWS_DIR)) return '

新聞目錄不存在

'; $files = []; $dh = opendir(NEWS_DIR); while (($fname = readdir($dh)) !== false) { if ($fname === '.' || $fname === '..') continue; $path = NEWS_DIR . $fname; if (is_file($path) && pathinfo($fname, PATHINFO_EXTENSION) === 'txt') { $files[$fname] = filemtime($path); } } closedir($dh); if (!$files) return '

暫無新聞

'; // 依修改時間遞減排序 arsort($files); $html = ''; foreach ($files as $fname => $mtime) { $lines = file(NEWS_DIR . $fname, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $html .= ''; } $html .= '
'; $html .= '
' . date('Y-m-d H:i:s', $mtime) . '
'; foreach ($lines as $line) { $line = htmlspecialchars($line, ENT_QUOTES, 'UTF-8'); $line = parseLinks($line); $html .= '
' . $line . '
'; } $html .= '
'; return $html; } function parseLinks(string $text): string { // ${https://url} 或 ${https://url|文字} return preg_replace_callback( '/\$\{([^}]+)\}/', function ($m) { $content = $m[1]; if (strpos($content, '|') !== false) { [$url, $label] = explode('|', $content, 2); } else { $url = $label = $content; } $url = htmlspecialchars(trim($url), ENT_QUOTES, 'UTF-8'); $label = htmlspecialchars(trim($label), ENT_QUOTES, 'UTF-8'); return '' . $label . ''; }, $text ); } ?> <!DOCTYPE html> <html lang="zh-TW"> <head> <meta charset="UTF-8"> <title>最新消息</title> <style> .news-list { width: 100%; max-width: 800px; margin: 0 auto; border-collapse: collapse; } .news-item { padding: 16px; border-bottom: 1px solid #eee; } .news-meta { font-size: 0.85em; color: #666; margin-bottom: 8px; } .news-line { line-height: 1.6; } .news-line a { color: #0066cc; text-decoration: none; } .news-line a:hover { text-decoration: underline; } </style> </head> <body> <h1>最新消息</h1> <?= renderNews() ?> </body> </html>

文字檔範例 (data/news/20240115_announce.txt)

系統將於 ${https://example.com/maintain|2024-01-20 02:00-04:00} 進行維護。
新功能上線:${https://example.com/new-feature}
請留意公告。

部署建議

  • 新聞目錄設為 **不可直接 HTTP 存取** (放在 DocumentRoot 外或用 .htaccess 拒絕)。
  • 後台上傳/編輯新聞檔案即可即時生效,無需資料庫。
  • 大量新聞時可加入分頁 (陣列切片) 與快取 (filemtime 未變則讀取快取 HTML)。
  • 編碼統一 UTF-8,避免亂碼。

擴充想法

  1. 支援 Markdown 解析 (引入 erusev/parsedown)。
  2. 2. 加入分類/標籤 (檔名前綴:cat_news_... 或 JSON 中繼資料檔)。 3. 整合 RSS 輸出 (header('Content-Type: application/xml'))。 4. 管理介面:上傳、編輯、刪除、排序 (觸摸 mtime)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved