萬盛學電腦網

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

PHP 動態生成 RSS 2.0 訂閱源完整實現:通用 FeedCreator 類庫封裝

RSS(Really Simple Syndication)是內容分發標準格式,採用 XML 結構描述網站更新內容。本文提供一個功能完整的 PHP RSS 生成類庫,支援 RSS 0.91/2.0、自動截斷、CDATA 保護、樣式表引用、快取機制,可直接整合至部落格、新聞系統、播客平台。

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/article/1</link>
      <description><![CDATA[文章摘要或全文]]></description>
      <pubDate>Mon, 01 Jan 2024 12:00:00 +0800</pubDate>
      <guid>https://example.com/article/1</guid>
    </item>
  </channel>
</rss>

通用 FeedCreator 類庫核心代碼

<?php
define('TIME_ZONE', 'Asia/Taipei');
define('FEEDCREATOR_VERSION', 'https://example.com');

class FeedItem {
    public $title, $description, $link, $author, $authorEmail;
    public $date, $category, $comments, $guid, $source;
    public $descriptionHtmlSyndicated = true; // 允許 HTML
    public $descriptionTruncSize = 500;       // 自動截斷長度
}

class FeedImage {
    public $title, $url, $link, $width, $height, $description;
}

abstract class FeedCreator {
    public $title, $description, $link, $language = 'zh-TW';
    public $syndicationURL, $image, $copyright, $pubDate, $lastBuildDate;
    public $editor, $editorEmail, $webMaster, $category, $docs, $ttl, $rating;
    public $items = [];
    public $contentType = 'application/xml';
    public $encoding = 'utf-8';
    public $cssStyleSheet = '', $xslStyleSheet = '';
    public $additionalElements = [];

    abstract public function createFeed();

    protected function _createGeneratorComment() {
        return "<!-- generator=\"\"".FEEDCREATOR_VERSION."\"\" -->\n";
    }

    protected function _createAdditionalElements($elements, $indent = '') {
        $out = '';
        if (is_array($elements)) {
            foreach ($elements as $k => $v) {
                $out .= $indent . "<$k>$v</$k>\n";
            }
        }
        return $out;
    }

    public function addItem(FeedItem $item) {
        $this->items[] = $item;
    }

    public function saveFeed($filename = '', $display = true) {
        $feed = $this->createFeed();
        $filename = $filename ?: $this->_generateFilename();
        file_put_contents($filename, $feed);
        if ($display) $this->_redirect($filename);
    }

    public function useCached($filename = '', $timeout = 3600) {
        $filename = $filename ?: $this->_generateFilename();
        if (file_exists($filename) && (time() - filemtime($filename) < $timeout)) {
            $this->_redirect($filename);
        }
    }

    private function _generateFilename() {
        $info = pathinfo($_SERVER['PHP_SELF']);
        return $info['filename'] . '.xml';
    }

    private function _redirect($filename) {
        header("Content-Type: {$this->contentType}; charset={$this->encoding}; filename=" . basename($filename));
        header("Content-Disposition: inline; filename=" . basename($filename));
        readfile($filename);
        exit;
    }
}

class RSSCreator20 extends FeedCreator {
    public function createFeed() {
        $feed = "<?xml version=\"1.0\" encoding=\"{$this->encoding}\"?>\n";
        $feed .= $this->_createStylesheetReferences();
        $feed .= $this->_createGeneratorComment();
        $feed .= "<rss version=\"2.0\">\n<channel>\n";
        $feed .= "  <title>" . htmlspecialchars($this->title) . "</title>\n";
        $feed .= "  <link>" . htmlspecialchars($this->link) . "</link>\n";
        $feed .= "  <description>" . htmlspecialchars($this->description) . "</description>\n";
        $feed .= "  <language>{$this->language}</language>\n";
        if ($this->copyright) $feed .= "  <copyright>" . htmlspecialchars($this->copyright) . "</copyright>\n";
        if ($this->pubDate) $feed .= "  <pubDate>" . date('r', $this->pubDate) . "</pubDate>\n";
        if ($this->lastBuildDate) $feed .= "  <lastBuildDate>" . date('r', $this->lastBuildDate) . "</lastBuildDate>\n";
        if ($this->image) {
            $feed .= "  <image>\n";
            $feed .= "    <title>" . htmlspecialchars($this->image->title) . "</title>\n";
            $feed .= "    <url>" . htmlspecialchars($this->image->url) . "</url>\n";
            $feed .= "    <link>" . htmlspecialchars($this->image->link) . "</link>\n";
            $feed .= "  </image>\n";
        }
        $feed .= $this->_createAdditionalElements($this->additionalElements, '  ');

        foreach ($this->items as $item) {
            $feed .= "  <item>\n";
            $feed .= "    <title>" . htmlspecialchars($item->title) . "</title>\n";
            $feed .= "    <link>" . htmlspecialchars($item->link) . "</link>\n";
            $feed .= "    <description>" . $item->getDescription() . "</description>\n";
            if ($item->author) $feed .= "    <author>" . htmlspecialchars($item->authorEmail) . " (" . htmlspecialchars($item->author) . ")</author>\n";
            if ($item->category) $feed .= "    <category>" . htmlspecialchars($item->category) . "</category>\n";
            if ($item->comments) $feed .= "    <comments>" . htmlspecialchars($item->comments) . "</comments>\n";
            if ($item->guid) $feed .= "    <guid isPermaLink=\"true\">" . htmlspecialchars($item->guid) . "</guid>\n";
            if ($item->date) $feed .= "    <pubDate>" . date('r', $item->date) . "</pubDate>\n";
            $feed .= $this->_createAdditionalElements($item->additionalElements, '    ');
            $feed .= "  </item>\n";
        }
        $feed .= "</channel>\n</rss>";
        return $feed;
    }
}

// 統一入口
class UniversalFeedCreator extends FeedCreator {
    private $_feed;
    public function _setFormat($format) {
        switch (strtoupper($format)) {
            case 'RSS2.0': case '2.0': $this->_feed = new RSSCreator20(); break;
            default: $this->_feed = new RSSCreator20();
        }
        foreach (get_object_vars($this) as $k => $v) {
            if (!in_array($k, ['_feed','contentType','encoding'])) $this->_feed->$k = $v;
        }
    }
    public function createFeed($format = 'RSS2.0') { $this->_setFormat($format); return $this->_feed->createFeed(); }
    public function saveFeed($format = 'RSS2.0', $filename = '', $display = true) { $this->_setFormat($format); $this->_feed->saveFeed($filename, $display); }
    public function useCached($format = 'RSS2.0', $filename = '', $timeout = 3600) { $this->_setFormat($format); $this->_feed->useCached($filename, $timeout); }
}
?>

使用範例

<?php
require 'FeedCreator.php';

$feed = new UniversalFeedCreator();
$feed->title = '我的技術部落格';
$feed->link = 'https://blog.example.com';
$feed->description = '分享 PHP、Laravel、架構設計心得';
$feed->language = 'zh-TW';
$feed->copyright = 'Copyright © 2024';

$feed->image = new FeedImage();
$feed->image->title = '部落格 Logo';
$feed->image->url = 'https://blog.example.com/logo.png';
$feed->image->link = 'https://blog.example.com';

// 模擬從資料庫讀取文章
$articles = [
    ['id'=>1, 'title'=>'PHP 8.2 新特性', 'url'=>'https://blog.example.com/1', 'summary'=>'...', 'time'=>strtotime('-1 day')],
    ['id'=>2, 'title'=>'Laravel 隊列實戰', 'url'=>'https://blog.example.com/2', 'summary'=>'...', 'time'=>strtotime('-2 day')],
];

foreach ($articles as $a) {
    $item = new FeedItem();
    $item->title = $a['title'];
    $item->link = $a['url'];
    $item->description = $a['summary'];
    $item->date = $a['time'];
    $item->guid = $a['url'];
    $feed->addItem($item);
}

// 直接輸出到瀏覽器
$feed->createFeed('RSS2.0');

// 或儲存快取檔案(1小時更新一次)
// $feed->useCached('RSS2.0', 'rss.xml', 3600);
// $feed->saveFeed('RSS2.0', 'rss.xml');
?>

進階功能說明

  • HTML 內容保護:$item->descriptionHtmlSyndicated = true 會用 CDATA 包裹,避免 HTML 標籤破壞 XML 結構
  • 自動摘要截斷:$item->descriptionTruncSize = 300 智能在句號/空格處截斷並加 ...
  • CSS/XSL 樣式表:設定 $feed->cssStyleSheet 或 xslStyleSheet 讓瀏覽器直接美化顯示
  • 快取機制:useCached() 檢查檔案修改時間,未過期直接輸出靜態檔,大幅降低資料庫壓力
  • 擴展元素:$feed->additionalElements['atom:link'] = '...' 支援 Atom、iTunes 等擴展命名空間

部署建議

  1. 建立獨立 rss.php 入口,設定 Nginx 快取規則
  2. 配合 Last-Modified/ETag 支援條件請求
  3. 提交至 RSS 聚合平台(Feedly、Inoreader)驗證格式
  4. 大流量站點建議預生成靜態 XML,由排程任務定時更新

標準化的 RSS 輸出能讓內容無縫觸達訂閱用戶,是內容型網站不可或缺的基礎設施。

copyright © 萬盛學電腦網 all rights reserved