萬盛學電腦網

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

PHP 解析 RSS/Atom 訂閱源:SimpleXML 實作內容聚合

RSS 2.0 結構速覽

<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
  <channel>
    <title>頻道標題</title>
    <link>https://example.com</link>
    <description>頻道描述</description>
    <language>zh-TW</language>
    <item>
      <title>文章標題</title>
      <link>https://example.com/post/1</link>
      <description><![CDATA[文章摘要或全文]]></description>
      <pubDate>Mon, 01 Jan 2024 00:00:00 +0800</pubDate>
      <guid isPermaLink="true">https://example.com/post/1</guid>
      <category>分類</category>
      <author>author@example.com</author>
    </item>
  </channel>
</rss>

SimpleXML 解析範例

<?php
function fetchRss(string $url, int $limit = 10): array {
    $ctx = stream_context_create([
        'http' => [
            'timeout' => 10,
            'user_agent' => 'Mozilla/5.0 (compatible; RSSReader/1.0)',
            'header' => "Accept: application/rss+xml, application/atom+xml, application/xml\r\n"
        ],
        'ssl' => ['verify_peer' => false, 'verify_peer_name' => false] // 僅測試用
    ]);

    $xmlString = @file_get_contents($url, false, $ctx);
    if ($xmlString === false) {
        throw new Exception("無法獲取 RSS: $url");
    }

    $xml = simplexml_load_string($xmlString);
    if ($xml === false) {
        throw new Exception("XML 解析失敗");
    }

    $items = [];
    // RSS 2.0
    if (isset($xml->channel->item)) {
        foreach ($xml->channel->item as $item) {
            $items[] = parseRssItem($item);
            if (count($items) >= $limit) break;
        }
    }
    // Atom 1.0
    elseif (isset($xml->entry)) {
        foreach ($xml->entry as $entry) {
            $items[] = parseAtomEntry($entry);
            if (count($items) >= $limit) break;
        }
    }

    return $items;
}

function parseRssItem(SimpleXMLElement $item): array {
    return [
        'title' => (string)($item->title ?? ''),
        'link' => (string)($item->link ?? ''),
        'description' => (string)($item->description ?? ''),
        'pubDate' => isset($item->pubDate) ? strtotime((string)$item->pubDate) : null,
        'guid' => (string)($item->guid ?? ''),
        'categories' => array_map('strval', $item->xpath('category')),
        'author' => (string)($item->author ?? ''),
        'enclosure' => $item->enclosure ? [
            'url' => (string)$item->enclosure['url'],
            'type' => (string)$item->enclosure['type'],
            'length' => (int)$item->enclosure['length']
        ] : null,
    ];
}

function parseAtomEntry(SimpleXMLElement $entry): array {
    $link = '';
    foreach ($entry->link as $l) {
        if ((string)$l['rel'] === 'alternate' || (string)$l['rel'] === '') {
            $link = (string)$l['href'];
            break;
        }
    }
    return [
        'title' => (string)($entry->title ?? ''),
        'link' => $link,
        'description' => (string)($entry->summary ?? $entry->content ?? ''),
        'pubDate' => isset($entry->published) ? strtotime((string)$entry->published) : null,
        'guid' => (string)($entry->id ?? ''),
        'categories' => array_map(fn($c) => (string)$c['term'], $entry->xpath('category')),
        'author' => (string)($entry->author->name ?? ''),
    ];
}

// 使用
try {
    $articles = fetchRss('https://rss.example.com/feed.xml', 5);
    foreach ($articles as $art) {
        echo "<h3><a href='{$art['link']}'>{$art['title']}</a></h3>";
        echo "<small>" . date('Y-m-d H:i', $art['pubDate'] ?? 0) . "</small>";
        echo "<div>{$art['description']}</div>";
    }
} catch (Exception $e) {
    echo "載入失敗: " . $e->getMessage();
}
?>

命名空間處理 (Atom、Media RSS、iTunes 等)

$xml->registerXPathNamespace('atom', 'https://www.w3.org/2005/Atom');
$xml->registerXPathNamespace('media', 'https://search.yahoo.com/mrss/');
$xml->registerXPathNamespace('itunes', 'https://www.itunes.com/dtds/podcast-1.0.dtd');

$mediaThumbs = $xml->xpath('//media:thumbnail');
$itunesDuration = (string)$xml->xpath('//itunes:duration')[0];

快取策略 (避免頻繁請求來源站)

function fetchRssCached(string $url, int $ttl = 3600): 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), LOCK_EX);
    return $data;
}

常見問題與對策

問題對策
編碼錯誤 (亂碼)XML 宣告 encoding、SimpleXML 自動轉 UTF-8、必要時 mb_convert_encoding
CDATA 內容包含 HTML 標籤直接輸出 (已是字串),前端用 htmlspecialchars 或受信任過濾器
大檔案記憶體耗盡改用 XMLReader 流式解析
來源站封鎖/限流設定 User-Agent、快取、錯誤重試、代理池
相對路徑連結用 parse_url($base) 解析後組合絕對 URL

現代替代:使用成熟庫

composer require rss-php/rss-php
# 或
composer require simplepie/simplepie

提供:快取、多格式支援、圖片提取、清理、PSR-16 快取整合。

copyright © 萬盛學電腦網 all rights reserved