萬盛學電腦網

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

PHP 生成 RSS 2.0 訂閱源:完整類實現與使用指南

前言

RSS (Really Simple Syndication) 是內容分發的標準格式。PHP 原生 XML 操作雖強大,但手動拼接字符串易出錯。本文提供一個健壯的 RSSGenerator 類,支援 RSS 2.0 規範、CDATA 內容、多項目管理、文件快取與直接輸出。

RSSGenerator 類完整代碼

<?php
/**
 * RSS 2.0 生成器
 * 使用範例:
 * $rss = new RSSGenerator('我的部落格', 'https://example.com', '技術分享');
 * $rss->addItem('文章標題', 'https://example.com/post/1', '文章摘要...', '2024-01-15 10:30:00');
 * $rss->saveToFile('rss.xml'); // 或 $rss->output();
 */
class RSSGenerator {
    // 頻道元數據
    private string $title;
    private string $link;
    private string $description;
    private string $language = 'zh-TW';
    private string $copyright = '';
    private string $webMaster = '';
    private string $pubDate = '';
    private string $lastBuildDate = '';
    private string $generator = 'PHP RSSGenerator/1.0';
    private array $items = [];

    public function __construct(string $title, string $link, string $description) {
        $this->title = $title;
        $this->link = rtrim($link, '/');
        $this->description = $description;
        $this->pubDate = $this->lastBuildDate = date(DATE_RSS);
    }

    // 設定器鏈式調用
    public function setLanguage(string $lang): self { $this->language = $lang; return $this; }
    public function setCopyright(string $copyright): self { $this->copyright = $copyright; return $this; }
    public function setWebMaster(string $email): self { $this->webMaster = $email; return $this; }
    public function setGenerator(string $gen): self { $this->generator = $gen; return $this; }

    /**
     * 添加條目
     * @param string $title 標題
     * @param string $link  永久鏈接
     * @param string $description 內容 (支援 HTML,自動包裹 CDATA)
     * @param string|DateTime $pubDate 發布時間
     * @param string $guid 唯一標識 (預設同 link)
     * @param array $enclosures 附件 [['url'=>'', 'type'=>'', 'length'=>''], ...]
     */
    public function addItem(
        string $title,
        string $link,
        string $description,
        $pubDate = '',
        string $guid = '',
        array $enclosures = []
    ): self {
        $pubDate = $pubDate ? (is_string($pubDate) ? $pubDate : $pubDate->format(DATE_RSS)) : date(DATE_RSS);
        $guid = $guid ?: $link;
        $this->items[] = compact('title', 'link', 'description', 'pubDate', 'guid', 'enclosures');
        $this->lastBuildDate = date(DATE_RSS); // 更新最後構建時間
        return $this;
    }

    /** 生成完整 XML 字符串 */
    public function build(): string {
        $xml = '' . "\n";
        $xml .= '' . "\n";
        $xml .= '  ' . "\n";

        // 頻道必要元素
        $xml .= $this->elem('title', $this->title);
        $xml .= $this->elem('link', $this->link);
        $xml .= $this->elem('description', $this->description);
        $xml .= $this->elem('language', $this->language);
        $xml .= $this->elem('generator', $this->generator);
        $xml .= $this->elem('pubDate', $this->pubDate);
        $xml .= $this->elem('lastBuildDate', $this->lastBuildDate);
        if ($this->copyright) $xml .= $this->elem('copyright', $this->copyright);
        if ($this->webMaster) $xml .= $this->elem('webMaster', $this->webMaster);
        // Atom 自我引用
        $xml .= '    ' . "\n";

        // 項目
        foreach ($this->items as $item) {
            $xml .= '    ' . "\n";
            $xml .= $this->elem('title', $item['title'], 6);
            $xml .= $this->elem('link', $item['link'], 6);
            $xml .= $this->cdataElem('description', $item['description'], 6);
            $xml .= $this->elem('pubDate', $item['pubDate'], 6);
            $xml .= $this->elem('guid', $item['guid'], 6, ['isPermaLink' => 'true']);
            // 附件
            foreach ($item['enclosures'] as $enc) {
                $attrs = ' url="' . htmlspecialchars($enc['url']) . '"';
                $attrs .= ' type="' . htmlspecialchars($enc['type']) . '"';
                $attrs .= ' length="' . htmlspecialchars($enc['length']) . '"';
                $xml .= '      ' . "\n";
            }
            $xml .= '    ' . "\n";
        }

        $xml .= '  ' . "\n";
        $xml .= '';
        return $xml;
    }

    /** 直接輸出至瀏覽器 (附正確 Header) */
    public function output(): void {
        header('Content-Type: application/rss+xml; charset=UTF-8');
        echo $this->build();
    }

    /** 保存至文件 */
    public function saveToFile(string $filename): bool {
        $content = $this->build();
        $bytes = file_put_contents($filename, $content, LOCK_EX);
        return $bytes !== false;
    }

    // --- 內部輔助方法 ---
    private function elem(string $name, string $value, int $indent = 4, array $attrs = []): string {
        $str = str_repeat(' ', $indent) . "<$name";
        foreach ($attrs as $k => $v) $str .= " $k=\"$v\"";
        $str .= '>' . htmlspecialchars($value, ENT_XML1 | ENT_DISALLOWED, 'UTF-8') . "\n";
        return $str;
    }

    private function cdataElem(string $name, string $value, int $indent = 4): string {
        // 確保 CDATA 內無 ']]>' 序列
        $value = str_replace(']]>', ']]>', $value);
        return str_repeat(' ', $indent) . "<$name>\n";
    }
}

使用範例

<?php
require_once 'RSSGenerator.php';

$rss = new RSSGenerator(
    '技術部落格',
    'https://blog.example.com',
    '分享 PHP、架構、運維實戰經驗'
)->setLanguage('zh-TW')
 ->setCopyright('Copyright 2024, Tech Blog')
 ->setWebMaster('admin@example.com');

// 從資料庫獲取文章 (模擬)
$posts = [
    ['title' => 'PHP 8.2 新特性速覽', 'slug' => 'php-82-features', 'excerpt' => 'readonly 類、DNF 型別...', 'date' => '2024-01-20 09:00:00'],
    ['title' => 'Docker 多階段構建最佳實踐', 'slug' => 'docker-multi-stage', 'excerpt' => '減小鏡像體積 80%...', 'date' => '2024-01-18 14:30:00'],
];

foreach ($posts as $post) {
    $rss->addItem(
        $post['title'],
        "https://blog.example.com/post/{$post['slug']}",
        $post['excerpt'],
        $post['date']
    );
}

// 方式 1: 直接輸出 (適用於路由 /rss.xml)
$rss->output();

// 方式 2: 定時任務生成靜態文件 (高流量推薦)
// $rss->saveToFile(__DIR__ . '/public/rss.xml');

進階功能擴展

1. 支援分類

// 在 addItem 參數增加 $categories = []
// XML 中添加:
foreach ($item['categories'] as $cat) {
    $xml .= $this->elem('category', $cat, 6, ['domain' => 'blog.example.com/categories']);
}

2. 圖片/媒體附件 (Media RSS)

$rss->addItem(..., [
    ['url' => 'https://example.com/img/cover.jpg', 'type' => 'image/jpeg', 'length' => '123456']
]);

3. 快取策略

// 簡單文件快取,15 分鐘更新一次
$cacheFile = __DIR__ . '/cache/rss.xml';
$cacheTime = 900; // 秒

if (!file_exists($cacheFile) || time() - filemtime($cacheFile) > $cacheTime) {
    $rss->saveToFile($cacheFile);
}
readfile($cacheFile);

RSS 2.0 規範要點速查

  • 編碼: 必須 UTF-8,XML 聲明指定 encoding="UTF-8"。
  • 日期格式: RFC 822 / RFC 2822,PHP 常量 DATE_RSS 即為標準格式 (如 Mon, 20 Jan 2024 09:00:00 +0000)。
  • HTML 內容: <description> 必須用 CDATA 區塊包裹,避免實體編碼雙重轉義。
  • GUID: 每項需唯一標識,isPermaLink="true" 表示 GUID 即永久鏈接。
  • 原子鏈接: 建議加入 <atom:link rel="self" ...> 利於閱讀器發現。

結語

一個乾淨、符合規範的 RSS 生成類,能讓你的內容輕鬆被 Feedly、Inoreader、NetNewsWire 等閱讀器訂閱。本文提供的 RSSGenerator 類結構清晰、擴展性強,可直接投入生產環境。配合定時任務生成靜態 XML 文件,更能承擔百萬級訂閱流量而無壓力。

copyright © 萬盛學電腦網 all rights reserved