代码说话。
header('Content-Type: application/xml', true); //set document header content type to be XML
$rss = new SimpleXMLExtendedModel('<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom"></rss>');
$rss->addAttribute('version', '2.0');
$channel = $rss->addChild('channel'); //add channel node
$atom = $channel->addChild('atom:atom:link');
$atom->addAttribute('href', '你的RSS链接');
$atom->addAttribute('rel', 'self');
$atom->addAttribute('type', 'application/rss+xml');
$channel->addChild('title', 'RSS标题');
$description = $channel->addChild('description', 'RSS描述');
$link = $channel->addChild('link', '你的RSS链接');
$language = $channel->addChild('language', 'zh-Hans');
$lastBuildDate = new DateTime($date . ' 02:00:00');
$channel->addChild('lastBuildDate', $lastBuildDate->format(DateTime::RSS));
$channel->addChild('pubDate', $lastBuildDate->format(DateTime::RSS));
$generator = $channel->addChild('generator', '创建者');
// $result 为数据库查询结果
foreach ($result as $data) {
$item = $channel->addChild('item');
$item->addChild('title', 'item的标题');
$link = $item->addChild('link', 'item的链接');
$guid = $item->addChild('guid', 'item的链接');
$guid->addAttribute('isPermaLink', 'true');
$item->addChild('description')->addCData('item的描述');
$item = $item->addChild('pubDate', $lastBuildDate->format(DateTime::RSS)); //add pubDate node
}
echo $rss->asXML();
期间遇到CDATA的问题,解决方案新增一个扩展类。
class SimpleXMLExtendedModel extends SimpleXMLElement {
public function addCData($cdata_text) {
$node= dom_import_simplexml($this);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($cdata_text));
return true;
}
}