萬盛學電腦網

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

PHP 新手入門:使用 SimpleXML 解析 RSS 2.0 建立閱讀器

RSS 2.0 結構速覽

<?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>

SimpleXML 解析器(PHP 5.1+ 內建)

<?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>";
}

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

$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)
);

定時任務抓取 → 寫入資料庫 → 前端讀取資料庫,支援全文搜尋、分類、標籤。

現代替代:PHP 8.1+ DOMDocument + XPath

$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 更穩健處理編碼、命名空間、大檔案。

copyright © 萬盛學電腦網 all rights reserved