${https://url} 或 ${https://url|顯示文字}。
4. 自動轉義 HTML 特殊字元,防 XSS。
<?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 .= '';
foreach ($lines as $line) {
$line = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
$line = parseLinks($line);
$html .= '' . $line . '';
}
$html .= ' ';
}
$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>
系統將於 ${https://example.com/maintain|2024-01-20 02:00-04:00} 進行維護。
新功能上線:${https://example.com/new-feature}
請留意公告。
erusev/parsedown)。cat_news_... 或 JSON 中繼資料檔)。
3. 整合 RSS 輸出 (header('Content-Type: application/xml'))。
4. 管理介面:上傳、編輯、刪除、排序 (觸摸 mtime)。