php 实现 feed
PHP 实现 Feed(RSS/Atom)
PHP 可以通过生成 XML 格式的数据来实现 RSS 或 Atom Feed。以下是两种常见的 Feed 实现方法:
RSS Feed 实现
RSS 是一种常用的 Feed 格式,适用于博客、新闻等内容聚合。以下是一个简单的 RSS 生成示例:
<?php
header("Content-Type: application/rss+xml; charset=UTF-8");
$rss = '<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>网站标题</title>
<link>https://example.com</link>
<description>网站描述</description>
<language>zh-cn</language>';
// 假设 $articles 是从数据库获取的文章列表
$articles = [
['title' => '文章1', 'link' => 'https://example.com/article1', 'description' => '文章1描述', 'pubDate' => 'Mon, 01 Jan 2023 00:00:00 GMT'],
['title' => '文章2', 'link' => 'https://example.com/article2', 'description' => '文章2描述', 'pubDate' => 'Tue, 02 Jan 2023 00:00:00 GMT']
];
foreach ($articles as $article) {
$rss .= '
<item>
<title>' . htmlspecialchars($article['title']) . '</title>
<link>' . htmlspecialchars($article['link']) . '</link>
<description>' . htmlspecialchars($article['description']) . '</description>
<pubDate>' . $article['pubDate'] . '</pubDate>
</item>';
}
$rss .= '
</channel>
</rss>';
echo $rss;
?>
Atom Feed 实现
Atom 是另一种 Feed 格式,比 RSS 更标准化。以下是 Atom Feed 的生成示例:
<?php
header("Content-Type: application/atom+xml; charset=UTF-8");
$atom = '<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>网站标题</title>
<link href="https://example.com" />
<updated>' . date(DATE_ATOM) . '</updated>
<author>
<name>作者名称</name>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>';
// 假设 $articles 是从数据库获取的文章列表
$articles = [
['title' => '文章1', 'link' => 'https://example.com/article1', 'summary' => '文章1摘要', 'updated' => '2023-01-01T00:00:00+00:00'],
['title' => '文章2', 'link' => 'https://example.com/article2', 'summary' => '文章2摘要', 'updated' => '2023-01-02T00:00:00+00:00']
];
foreach ($articles as $article) {
$atom .= '
<entry>
<title>' . htmlspecialchars($article['title']) . '</title>
<link href="' . htmlspecialchars($article['link']) . '" />
<id>' . htmlspecialchars($article['link']) . '</id>
<updated>' . $article['updated'] . '</updated>
<summary>' . htmlspecialchars($article['summary']) . '</summary>
</entry>';
}
$atom .= '
</feed>';
echo $atom;
?>
使用第三方库
对于更复杂的 Feed 生成需求,可以使用专门的 PHP 库:
-
Laminas Feed (原 Zend Feed)
require 'vendor/autoload.php'; use Laminas\Feed\Writer\Feed; $feed = new Feed; $feed->setTitle('网站标题'); $feed->setLink('https://example.com'); $feed->setDescription('网站描述'); // 添加条目 $entry = $feed->createEntry(); $entry->setTitle('文章标题'); $entry->setLink('https://example.com/article1'); $entry->setDescription('文章描述'); $entry->setDateModified(time()); $feed->addEntry($entry); echo $feed->export('rss'); -
SimplePie (用于解析和生成 Feed)
require 'simplepie/autoloader.php'; $feed = new SimplePie(); $feed->set_feed_url('https://example.com/feed.rss'); $feed->init();
注意事项
- 确保设置正确的 Content-Type 头
- 对输出内容进行适当的转义 (使用 htmlspecialchars)
- 遵循 Feed 规范的时间格式 (RSS 使用 RFC 822, Atom 使用 ISO 8601)
- 对于动态内容,考虑使用缓存机制提高性能
这两种方法都可以根据实际需求进行调整,添加更多元素如分类、作者信息等。







