php 生成 RSS 订阅
编辑于 2022-04-03 15:45:10 阅读 1072
rss文件本身是xml,只要找到它的规范,使用php 数组转xml 就可以了
代码实现
$data=[
'title'=>'写代码的崔哥',
'link'=>'https://www.cuiwei.net/',
'description'=>'一名PHP程序员,涉猎广泛:PHP,运维,前端,Android,iOS。会不定期给大家分享一些技术干货',
'language'=>'zh-cn',
'pubDate'=>gmdate ('l d F Y H:i:s', time()).' GMT',
'lastBuildDate'=>gmdate ('l d F Y H:i:s', time()).' GMT',
'docs'=>'https://www.rssboard.org/rss-specification',
'generator'=>'cwf 1.0',
'managingEditor'=>'chudaozhe@outlook.com (cw)',
'webMaster'=>'chudaozhe@outlook.com (cw)',
];
$data['item']=[
[
'title' => 'aaa',
'link' => 'https://www.cuiwei.net/p/1203489253',
'description' => '描述。。。',
'pubDate' => gmdate('l d F Y H:i:s', time()).' GMT',
'guid' => '1203489253',
],
[
'title' => 'bbb',
'link' => 'https://www.cuiwei.net/p/1126078311',
'description' => '描述。。。',
'pubDate' => gmdate('l d F Y H:i:s', time()).' GMT',
'guid' => '1126078311',
],
];
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><rss version="2.0"></rss>');
array_to_xml(['channel'=>$data], $xml);
echo $xml->asXML();
function array_to_xml($array, $xml=null){
if (is_array($array)){
foreach($array as $key=>$value){
if(is_int($key)){
if($key==0){
$node=$xml;
}else{
$parent=$xml->xpath('..')[0];
$node=$parent->addChild($xml->getName());
}
}else{
$node=$xml->addChild($key);
}
array_to_xml($value, $node);
}
}else{
$xml[0]=$array;
}
}
结果
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>写代码的崔哥</title>
<link>https://www.cuiwei.net/</link>
<description>一名PHP程序员,涉猎广泛:PHP,运维,前端,Android,iOS。会不定期给大家分享一些技术干货</description>
<language>zh-cn</language>
<pubDate>Sunday 03 April 2022 07:50:50 GMT</pubDate>
<lastBuildDate>Sunday 03 April 2022 07:50:50 GMT</lastBuildDate>
<docs>https://www.rssboard.org/rss-specification</docs>
<generator>cwf 1.0</generator>
<managingEditor>chudaozhe@outlook.com (cw)</managingEditor>
<webMaster>chudaozhe@outlook.com (cw)</webMaster>
<item>
<title>aaa</title>
<link>https://www.cuiwei.net/p/1203489253</link>
<description>描述。。。</description>
<pubDate>Sunday 03 April 2022 07:50:50 GMT</pubDate>
<guid>1203489253</guid>
</item>
<item>
<title>bbb</title>
<link>https://www.cuiwei.net/p/1126078311</link>
<description>描述。。。</description>
<pubDate>Sunday 03 April 2022 07:50:50 GMT</pubDate>
<guid>1126078311</guid>
</item>
</channel>
</rss>