RSS(Really Simple Syndication)是內容發佈的標準格式,讓使用者透過訂閱工具即時獲取最新文章。本文示範如何使用 PHP DOMDocument 依據 RSS 2.0 規範,動態產生合規的 XML 訂閱源。
<?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>
<lastBuildDate>Wed, 02 Aug 2023 12:00:00 +0800</lastBuildDate>
<item>
<title>文章標題</title>
<link>https://example.com/post/1</link>
<description><![CDATA[文章摘要或全文 HTML]]></description>
<pubDate>Wed, 02 Aug 2023 10:00:00 +0800</pubDate>
<guid isPermaLink="true">https://example.com/post/1</guid>
</item>
...
</channel>
</rss>
<?php
class RssFeedGenerator
{
private DOMDocument $dom;
private DOMElement $channel;
public function __construct(
string $title,
string $link,
string $description,
string $language = 'zh-TW'
) {
$this->dom = new DOMDocument('1.0', 'UTF-8');
$this->dom->formatOutput = true; // 縮排輸出,方便除錯
$rss = $this->dom->createElement('rss');
$rss->setAttribute('version', '2.0');
$this->dom->appendChild($rss);
$this->channel = $this->dom->createElement('channel');
$rss->appendChild($this->channel);
$this->addElement('title', $title);
$this->addElement('link', $link);
$this->addElement('description', $description);
$this->addElement('language', $language);
$this->addElement('lastBuildDate', gmdate('r')); // RFC 2822 格式
}
/** 新增 channel 子元素 */
private function addElement(string $name, string $value): void
{
$el = $this->dom->createElement($name);
$el->appendChild($this->dom->createTextNode($value));
$this->channel->appendChild($el);
}
/** 新增文章項目 */
public function addItem(array $item): void
{
$itemEl = $this->dom->createElement('item');
$this->channel->appendChild($itemEl);
// 必要欄位
$this->appendChild($itemEl, 'title', $item['title']);
$this->appendChild($itemEl, 'link', $item['link']);
$this->appendChild($itemEl, 'description', $item['description'], true); // CDATA
$this->appendChild($itemEl, 'pubDate', $item['pubDate'] ?? gmdate('r'));
// 唯一識別碼
$guid = $this->dom->createElement('guid', $item['guid'] ?? $item['link']);
$guid->setAttribute('isPermaLink', $item['isPermaLink'] ?? 'true');
$itemEl->appendChild($guid);
// 可選:作者、分類、圖片等
if (!empty($item['author'])) {
$this->appendChild($itemEl, 'author', $item['author']);
}
if (!empty($item['category'])) {
foreach ((array)$item['category'] as $cat) {
$this->appendChild($itemEl, 'category', $cat);
}
}
if (!empty($item['enclosure'])) {
$enc = $this->dom->createElement('enclosure');
$enc->setAttribute('url', $item['enclosure']['url']);
$enc->setAttribute('type', $item['enclosure']['type'] ?? 'audio/mpeg');
$enc->setAttribute('length', $item['enclosure']['length'] ?? '0');
$itemEl->appendChild($enc);
}
}
private function appendChild(DOMElement $parent, string $name, string $value, bool $cdata = false): void
{
$el = $this->dom->createElement($name);
if ($cdata) {
$el->appendChild($this->dom->createCDATASection($value));
} else {
$el->appendChild($this->dom->createTextNode($value));
}
$parent->appendChild($el);
}
/** 輸出 XML 字串 */
public function render(): string
{
return $this->dom->saveXML();
}
/** 直接輸出至瀏覽器(含正確 Header) */
public function output(): void
{
header('Content-Type: application/rss+xml; charset=UTF-8');
echo $this->render();
}
}
<?php
require_once 'RssFeedGenerator.php';
// 模擬資料庫查詢結果
$posts = [
[
'title' => 'PHP 8.2 新特性深度解析',
'link' => 'https://example.com/post/php82-features',
'description' => 'PHP 8.2 帶來了 readonly 類別、DNF 型別...
',
'pubDate' => 'Wed, 02 Aug 2023 10:00:00 +0800',
'author' => 'admin@example.com (站長)',
'category' => ['PHP', '後端開發'],
],
[
'title' => '使用 Docker 部署 Laravel 應用',
'link' => 'https://example.com/post/docker-laravel',
'description' => '從 Dockerfile 撰寫到 docker-compose 編排...
',
'pubDate' => 'Tue, 01 Aug 2023 15:30:00 +0800',
'category' => ['DevOps', 'Laravel'],
],
];
$feed = new RssFeedGenerator(
title: '技術部落格',
link: 'https://example.com',
description: '分享 PHP、Laravel、Docker 等後端開發實戰經驗'
);
foreach ($posts as $post) {
$feed->addItem($post);
}
// 直接輸出(適用於路由 /rss.xml)
$feed->output();
// 或取得字串存檔/快取
// file_put_contents('rss.xml', $feed->render());
$rss = $this->dom->createElement('rss');
$rss->setAttribute('version', '2.0');
$rss->setAttribute('xmlns:itunes', 'https://www.itunes.com/dtds/podcast-1.0.dtd');
$rss->setAttribute('xmlns:media', 'https://search.yahoo.com/mrss/');
$this->dom->appendChild($rss);
// 在 item 中加入 iTunes 標籤
$itunesAuthor = $this->dom->createElement('itunes:author', 'Podcast Host');
$itemEl->appendChild($itunesAuthor);
$itunesDuration = $this->dom->createElement('itunes:duration', '45:30');
$itemEl->appendChild($itunesDuration);
/rss.xml、/feed、/atom.xml 等常見路徑。使用 DOMDocument 產生 RSS 具備結構嚴謹、自動處理實體編碼、支援 CDATA 與命名空間等優點。搭配快取策略與標準路由,即可為你的部落格、播客、新聞站提供穩定的訂閱服務,讓內容觸達更多受眾。