pear install XML_RSS
pear install XML_Parser
# 或手動下載放入專案:RSS.php, Parser.php, PEAR.php
require_once 'RSS.php';
$url = 'https://example.com/feed.xml'; // 或本地檔案
$rss = new XML_RSS($url);
$rss->parse();
// 取得頻道資訊
$channel = $rss->getChannelInfo();
echo "頻道: {$channel['title']} - {$channel['description']}<br>";
// 取得所有項目
$items = $rss->getItems();
foreach ($items as $item) {
echo "<a href='{$item['link']}' target='_blank'>{$item['title']}</a><br>";
echo "發布: {$item['pubdate']}<br>";
echo "摘要: {$item['description']}<hr>";
}
// 取得圖片資訊
$images = $rss->getImages();
// 取得文字輸入區
$textinputs = $rss->getTextinputs();
實測三版本相容良好。
class MyXML_RSS extends XML_RSS {
public function __construct($url) {
parent::__construct($url);
// 覆寫 fetch 方法加入 curl 選項
}
}
PHP 5 內建,無需 PEAR:
// SimpleXML 範例
$xml = simplexml_load_file('feed.xml');
$namespaces = $xml->getNamespaces(true);
foreach ($xml->channel->item as $item) {
echo $item->title . '<br>';
// 處理命名空間 (dc:creator, content:encoded 等)
$content = $item->children($namespaces['content']);
echo $content->encoded;
}
// DOMDocument 範例(更強大、支援 XPath)
$dom = new DOMDocument();
$dom->load('feed.xml');
$xpath = new DOMXPath($dom);
$items = $xpath->query('//channel/item');
foreach ($items as $item) {
echo $xpath->evaluate('string(title)', $item) . '<br>';
}
libxml_use_internal_errors(true) 捕捉解析錯誤$rss->parse() 回傳值