萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 解析 RSS/Atom Feed 完整指南

前言

RSS (Really Simple Syndication) 與 Atom 是網站內容發佈標準格式。PHP 可用 SimpleXML、DOMDocument 或專用庫解析。本文提供現代、健壯的解析方案。

方法一:SimpleXML(簡單、足夠多數情境)

<?php
function parseRssSimpleXML($url, $limit = 20)
{
    $xml = simplexml_load_file($url);
    if (!$xml) return [];

    $items = [];
    $channel = $xml->channel ?? $xml; // RSS 2.0 有 channel,Atom 直接是 feed

    foreach ($channel->item ?? $channel->entry as $entry) {
        $item = [
            'title' => (string)($entry->title ?? ''),
            'link' => (string)($entry->link['href'] ?? $entry->link ?? ''),
            'description' => (string)($entry->description ?? $entry->summary ?? $entry->content ?? ''),
            'pubDate' => (string)($entry->pubDate ?? $entry->published ?? $entry->updated ?? ''),
            'guid' => (string)($entry->guid ?? $entry->id ?? ''),
        ];
        // 處理 Atom link@href
        if (empty($item['link']) && isset($entry->link['href'])) {
            $item['link'] = (string)$entry->link['href'];
        }
        $items[] = $item;
        if (count($items) >= $limit) break;
    }
    return $items;
}

// 使用
$items = parseRssSimpleXML('https://www.php.net/feed.atom');
foreach ($items as $item) {
    echo "<h3><a href='{$item['link']}'>{$item['title']}</a></h3>";
    echo "<p>{$item['description']}</p>";
}
?>

方法二:DOMDocument + XPath(更強大、支援命名空間)

<?php
function parseRssDOM($url, $limit = 20)
{
    $dom = new DOMDocument();
    $dom->load($url);
    $xpath = new DOMXPath($dom);

    // 註冊常見命名空間
    $xpath->registerNamespace('atom', 'https://www.w3.org/2005/Atom');
    $xpath->registerNamespace('dc', 'https://purl.org/dc/elements/1.1/');
    $xpath->registerNamespace('content', 'https://purl.org/rss/1.0/modules/content/');

    // 同時支援 RSS 2.0 (//item) 和 Atom (//atom:entry)
    $entries = $xpath->query('//item | //atom:entry');
    $items = [];

    foreach ($entries as $entry) {
        if (count($items) >= $limit) break;

        $title = $xpath->evaluate('string(title | atom:title)', $entry);
        $link = $xpath->evaluate('string(link/@href | atom:link/@href | link)', $entry);
        $desc = $xpath->evaluate('string(description | atom:summary | atom:content | content:encoded)', $entry);
        $date = $xpath->evaluate('string(pubDate | atom:published | atom:updated | dc:date)', $entry);
        $guid = $xpath->evaluate('string(guid | atom:id)', $entry);

        $items[] = compact('title', 'link', 'desc', 'date', 'guid');
    }
    return $items;
}
?>

方法三:使用成熟庫(推薦生產環境)

# Composer 安裝
composer require rss-php/rss-php

# 使用
<?php
require 'vendor/autoload.php';
use FeedIo\FeedIo;
use FeedIo\Reader\Document;

$feedIo = new FeedIo();
$feed = $feedIo->read('https://example.com/feed.xml');

foreach ($feed as $item) {
    echo $item->getTitle();
    echo $item->getLink();
    echo $item->getDescription();
    echo $item->getDate()->format('Y-m-d H:i:s');
}
?>

生成 RSS Feed(伺服器端)

<?php
header('Content-Type: application/rss+xml; charset=UTF-8');

$posts = [
    ['title' => '文章一', 'link' => 'https://example.com/1', 'desc' => '摘要一', 'date' => '2024-01-15 10:00:00'],
    ['title' => '文章二', 'link' => 'https://example.com/2', 'desc' => '摘要二', 'date' => '2024-01-14 15:30:00'],
];

echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<rss version="2.0">';
echo '<channel>';
echo '<title>我的部落格</title>';
echo '<link>https://example.com</link>';
echo '<description>最新文章</description>';
echo '<language>zh-TW</language>';
echo '<lastBuildDate>' . date(DATE_RSS) . '</lastBuildDate>';

foreach ($posts as $post) {
    echo '<item>';
    echo '<title><![CDATA[' . $post['title'] . ']]></title>';
    echo '<link>' . $post['link'] . '</link>';
    echo '<description><![CDATA[' . $post['desc'] . ']]></description>';
    echo '<pubDate>' . date(DATE_RSS, strtotime($post['date'])) . '</pubDate>';
    echo '<guid isPermaLink="true">' . $post['link'] . '</guid>';
    echo '</item>';
}
echo '</channel>';
echo '</rss>';
?>

快取與效能

  • 解析遠端 Feed 請務必快取(如 Redis、檔案快取 1-6 小時),避免每次請求都下載解析。
  • 設定 stream_context timeout 避免卡住。
$ctx = stream_context_create(['http' => ['timeout' => 10]]);
$xml = simplexml_load_file($url, 'SimpleXMLElement', 0, null, $ctx);

總結

SimpleXML 適合簡單需求;DOMDocument+XPath 處理複雜命名空間;生產環境建議使用 rss-php/rss-php 或 simplepie/simplepie 成熟庫,支援更多格式、錯誤處理、快取整合。

copyright © 萬盛學電腦網 all rights reserved