RSS (Really Simple Syndication) 是內容聚合的標準格式,許多部落格、新聞網站皆提供 RSS 訂閱。本文引導 PHP 初學者從零建立一個簡易 RSS 閱讀器,解析 XML 結構、提取標題、連結與描述,並示範如何搭配 MySQL 快取資料以提升效能。
標準 RSS 2.0 文件採用 XML 格式,核心結構如下:
<rss version="2.0">
<channel>
<title>網站標題</title>
<link>網站網址</link>
<description>網站描述</description>
<item>
<title>文章標題</title>
<link>文章連結</link>
<description>文章摘要</description>
<pubDate>發布時間</pubDate>
</item>
... 更多 <item> ...
</channel>
</rss>
關鍵標籤說明:
<channel>:頻道資訊容器<item>:單篇文章項目,可重複出現<title>、<link>、<description>:文章三要素解析策略:以 <item> 為單位迴圈,提取內部三個子標籤內容。PHP 內建 simplexml_load_file() 或 XMLReader 均可輕鬆處理。
$rss_url = "https://example.com/feed.xml";
$xml = simplexml_load_file($rss_url);
if ($xml) {
foreach ($xml->channel->item as $item) {
$title = (string)$item->title;
$link = (string)$item->link;
$desc = (string)$item->description;
$date = (string)$item->pubDate;
echo "<h3><a href='$link' target='_blank'>$title</a></h3>";
echo "<p>$desc</p>";
echo "<small>$date</small><hr>";
}
} else {
echo "無法載入 RSS 源";
}
頻繁請求遠端 RSS 會造成效能瓶頸,建議將解析結果存入 MySQL,定期更新。
CREATE TABLE rss_cache (
id INT AUTO_INCREMENT PRIMARY KEY,
feed_url VARCHAR(500) NOT NULL,
title VARCHAR(255),
link VARCHAR(500),
description TEXT,
pub_date DATETIME,
fetched_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_feed_url (feed_url)
);
// 檢查快取是否過期 (如 1 小時)
$stmt = $pdo->prepare("SELECT * FROM rss_cache WHERE feed_url = ? AND fetched_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$stmt->execute([$rss_url]);
$cached = $stmt->fetchAll();
if ($cached) {
// 直接使用快取資料
$items = $cached;
} else {
// 重新抓取並解析
$xml = simplexml_load_file($rss_url);
$items = [];
foreach ($xml->channel->item as $item) {
$items[] = [
'feed_url' => $rss_url,
'title' => (string)$item->title,
'link' => (string)$item->link,
'description' => (string)$item->description,
'pub_date' => date('Y-m-d H:i:s', strtotime((string)$item->pubDate))
];
}
// 批次寫入資料庫
$pdo->exec("DELETE FROM rss_cache WHERE feed_url = '$rss_url'");
$ins = $pdo->prepare("INSERT INTO rss_cache (feed_url, title, link, description, pub_date) VALUES (?, ?, ?, ?, ?)");
foreach ($items as $row) {
$ins->execute([$row['feed_url'], $row['title'], $row['link'], $row['description'], $row['pub_date']]);
}
}
// 顯示結果
foreach ($items as $item) {
// ... 輸出 HTML ...
}
stream_context_create() 設定 HTTP 逾時,避免腳本卡死。description 常含 HTML 實體,輸出前用 html_entity_decode() 處理。pubDate 排序,打造個人化資訊流。PHP 內建 XML 解析功能強大,配合 SimpleXML 或 XMLReader,幾行程式碼即可完成 RSS 閱讀器核心。加上資料庫快取與錯誤處理,即可構建穩定、高效的內容聚合應用。進階開發者可進一步整合關鍵字過濾、全文搜尋、推播通知等功能,打造專屬資訊助手。