php 实现 feed
实现 Feed 功能的基本方法
在 PHP 中实现 Feed 功能通常涉及生成 RSS 或 Atom 格式的 XML 文件。以下是实现 Feed 的基本步骤和代码示例。
创建 Feed 的基本结构
Feed 通常包含标题、链接、描述和条目列表。使用 PHP 的 SimpleXML 或手动构建 XML 字符串可以轻松实现。
<?php
header("Content-Type: application/xml; charset=utf-8");
$rss = new SimpleXMLElement('<rss version="2.0"></rss>');
$channel = $rss->addChild('channel');
$channel->addChild('title', 'My Feed Title');
$channel->addChild('link', 'http://example.com');
$channel->addChild('description', 'This is my feed description');
添加 Feed 条目
每个条目包含标题、链接、描述和发布时间。可以从数据库或其他数据源动态获取条目数据。
$items = [
['title' => 'Item 1', 'link' => 'http://example.com/item1', 'description' => 'Description for item 1', 'pubDate' => date(DATE_RSS)],
['title' => 'Item 2', 'link' => 'http://example.com/item2', 'description' => 'Description for item 2', 'pubDate' => date(DATE_RSS)]
];
foreach ($items as $item) {
$entry = $channel->addChild('item');
$entry->addChild('title', $item['title']);
$entry->addChild('link', $item['link']);
$entry->addChild('description', $item['description']);
$entry->addChild('pubDate', $item['pubDate']);
}
输出 Feed 内容
使用 asXML() 方法将生成的 XML 内容输出。
echo $rss->asXML();
使用数据库动态生成 Feed
从数据库获取数据并动态生成 Feed 条目。
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $db->query('SELECT title, link, description, created_at FROM posts ORDER BY created_at DESC LIMIT 10');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$entry = $channel->addChild('item');
$entry->addChild('title', $row['title']);
$entry->addChild('link', $row['link']);
$entry->addChild('description', $row['description']);
$entry->addChild('pubDate', date(DATE_RSS, strtotime($row['created_at'])));
}
支持 Atom 格式
Atom 是另一种常见的 Feed 格式,生成方式类似。
$atom = new SimpleXMLElement('<feed xmlns="http://www.w3.org/2005/Atom"></feed>');
$atom->addChild('title', 'My Atom Feed');
$atom->addChild('link', 'http://example.com/atom', ['href' => 'http://example.com/atom']);
$atom->addChild('updated', date(DATE_ATOM));
$entry = $atom->addChild('entry');
$entry->addChild('title', 'Item 1');
$entry->addChild('link', '', ['href' => 'http://example.com/item1']);
$entry->addChild('summary', 'Description for item 1');
$entry->addChild('updated', date(DATE_ATOM));
缓存 Feed 内容
为了提高性能,可以将生成的 Feed 内容缓存到文件或内存中。
$cacheFile = 'feed_cache.xml';
if (!file_exists($cacheFile) || time() - filemtime($cacheFile) > 3600) {
$content = $rss->asXML();
file_put_contents($cacheFile, $content);
}
readfile($cacheFile);
验证 Feed 格式
使用在线工具如 W3C Feed Validation Service 验证生成的 Feed 是否符合标准。
总结
通过 PHP 生成 Feed 功能简单且灵活,可以根据需求选择 RSS 或 Atom 格式,动态从数据库获取数据并缓存以提高性能。







