<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>站點標題</title>
<link>https://example.com</link>
<description>站點描述</description>
<item>
<title>文章標題</title>
<link>https://example.com/post/1</link>
<description>摘要內容</description>
<pubDate>Mon, 20 May 2024 14:30:05 +0800</pubDate>
<guid isPermaLink="true">https://example.com/post/1</guid>
</item>
...
</channel>
</rss>
<?php
function fetchRss(string $url, int $limit = 10): array
{
$xml = simplexml_load_file($url);
if ($xml === false) {
throw new RuntimeException('XML 解析失敗:' . libxml_get_last_error()->message);
}
$items = [];
foreach ($xml->channel->item as $item) {
$items[] = [
'title' => (string)$item->title,
'link' => (string)$item->link,
'description' => (string)$item->description,
'pubDate' => (string)$item->pubDate,
'guid' => (string)$item->guid,
];
if (count($items) >= $limit) break;
}
return $items;
}
// 使用
$feed = fetchRss('https://example.com/rss.xml', 5);
foreach ($feed as $entry) {
echo "<article><h2><a href='{$entry['link']}' target='_blank'>{$entry['title']}</a></h2>";
echo "<time>{$entry['pubDate']}</time>";
echo "<div>{$entry['description']}</div></article>";
}
$xml->registerXPathNamespace('atom', 'https://www.w3.org/2005/Atom');
$links = $xml->xpath('//atom:link[@rel="self"]');
function fetchRssCached(string $url, int $ttl = 300): array
{
$cacheKey = 'rss_' . md5($url);
$cacheFile = sys_get_temp_dir() . '/' . $cacheKey . '.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $ttl)) {
return json_decode(file_get_contents($cacheFile), true);
}
$data = fetchRss($url);
file_put_contents($cacheFile, json_encode($data));
return $data;
}
CREATE TABLE rss_cache (
id INT AUTO_INCREMENT PRIMARY KEY,
feed_url VARCHAR(500) NOT NULL,
item_guid VARCHAR(500) NOT NULL,
title TEXT,
link VARCHAR(500),
description TEXT,
pub_date DATETIME,
fetched_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uniq_feed_guid (feed_url, item_guid)
);
定時任務抓取 → 寫入資料庫 → 前端讀取資料庫,支援全文搜尋、分類、標籤。
$dom = new DOMDocument();
$dom->load($url);
$xpath = new DOMXPath($dom);
$items = $xpath->query('//channel/item');
foreach ($items as $item) {
$title = $xpath->evaluate('string(title)', $item);
// ...
}
DOMDocument 更穩健處理編碼、命名空間、大檔案。