首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 動態產生 RSS 訂閱完整實作指南

     編輯:PHP 綜合知識

什麼是 RSS?

RSS(Really Simple Syndication)是一種基於 XML 的內容聚合格式,廣泛用於部落格、新聞網站、Podcast 等內容發布。使用者透過 RSS 閱讀器即可在不造訪網站的情況下獲取最新更新。對網站營運者而言,提供 RSS 能提升內容觸達率與使用者留存。

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

PHP 完整產生器類別(簡化版)

以下類別封裝了 RSS 2.0 產生邏輯,支援動態加入項目、輸出 XML 字串或直接存檔:

class RssFeedGenerator
{
    private string $title;
    private string $link;
    private string $description;
    private string $language = 'zh-TW';
    private array  $items = [];

    public function __construct(string $title, string $link, string $description)
    {
        $this->title       = $title;
        $this->link        = $link;
        $this->description = $description;
    }

    public function addItem(string $title, string $link, string $description, string $pubDate = '', string $guid = ''): self
    {
        $this->items[] = [
            'title'       => $title,
            'link'        => $link,
            'description' => $description,
            'pubDate'     => $pubDate ?: date(DATE_RSS),
            'guid'        => $guid ?: $link,
        ];
        return $this;
    }

    public function setLanguage(string $lang): self
    {
        $this->language = $lang;
        return $this;
    }

    public function generate(): string
    {
        $xml = '';
        $xml .= '';
        $xml .= '' . $this->escape($this->title) . '';
        $xml .= '' . $this->escape($this->link) . '';
        $xml .= '' . $this->escape($this->description) . '';
        $xml .= '' . $this->language . '';
        $xml .= '' . date(DATE_RSS) . '';

        foreach ($this->items as $item) {
            $xml .= '';
            $xml .= '' . $this->escape($item['title']) . '';
            $xml .= '' . $this->escape($item['link']) . '';
            $xml .= '';
            $xml .= '' . $item['pubDate'] . '';
            $xml .= '' . $this->escape($item['guid']) . '';
            $xml .= '';
        }

        $xml .= '';
        return $xml;
    }

    public function output(): void
    {
        header('Content-Type: application/rss+xml; charset=utf-8');
        echo $this->generate();
    }

    public function save(string $path): bool
    {
        return (bool) file_put_contents($path, $this->generate());
    }

    private function escape(string $str): string
    {
        return htmlspecialchars($str, ENT_XML1 | ENT_QUOTES, 'UTF-8');
    }
}

使用範例:從資料庫產生 RSS

// 1. 連線資料庫(示範用 PDO)
$pdo = new PDO('mysql:host=localhost;dbname=blog;charset=utf8mb4', 'user', 'pass');
$stmt = $pdo->query('SELECT title, slug, excerpt, created_at FROM posts WHERE status="published" ORDER BY created_at DESC LIMIT 20');

// 2. 建立產生器
$feed = new RssFeedGenerator(
    '我的技術部落格',
    'https://blog.example.com',
    '分享程式開發心得與教學'
);

// 3. 迴圈加入項目
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $postUrl = 'https://blog.example.com/post/' . $row['slug'];
    $feed->addItem(
        $row['title'],
        $postUrl,
        $row['excerpt'],
        date(DATE_RSS, strtotime($row['created_at'])),
        $postUrl
    );
}

// 4. 輸出或存檔
// 直接輸出給瀏覽器/RSS 閱讀器
$feed->output();

// 或定期存檔為靜態 xml(搭配 cron job)
// $feed->save(__DIR__ . '/public/feed.xml');

部署與優化建議

  • 快取機制:RSS 內容變動頻率通常低於頁面,建議產生後快取 15~60 分鐘,減少資料庫查詢。
  • CDN 加速:將 feed.xml 部署至 CDN,降低主站流量。
  • 驗證工具:發布前用 W3C Feed Validation Service 驗證格式正確性。
  • 擴充欄位:依需求加入 <category>、<enclosure>(Podcast)、<author> 等標籤。

掌握 RSS 產生技術,能為你的內容建立標準化發布管道,觸達更多訂閱制使用者。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved