推荐扩展 :moell/rss
moell/rss是遵循RSS2.0标准的包
http://www.rssboard.org/rss-specification
PHP >= 5.4.0
composer require "moell/rss:1.*"
//设置字符集
public function setEncode($encode); //默认UTF-8
public function channel(array $channel);
public function item(array $item);
public function items(array $items);
//构造xml
public function build();
//快速构造
public function fastBuild(array $channel, array $item);
public function __toString();
$rss = new \\Moell\\Rss\\Rss();
$channel = [
'title' => 'title',
'link' => 'http://moell.cn',
'description' => 'description',
'category' => [
'value' => 'html',
'attr' => [
'domain' => 'http://www.moell.cn'
]
]
];
$rss->channel($channel);
$items = [];
for($i = 0; $i < 2; $i++) {
$item = [
'title' => "title".$i,
'description' => 'description',
'pubDate' => htmlspecialchars(date(DATE_RSS, strtotime($created_at))), # 注意时间格式
'source' => [
'value' => 'moell.cn',
'attr' => [
'url' => 'http://www.moell.cn'
]
]
];
$items[] = $item;
$rss->item($item);
}
echo $rss; //获取xml
//其他获取方式
$rss->build()->asXML();
$rss->fastBuild($channel, $items)->asXML();
$rss->channel($channel)->items($items)->build()->asXML();
若报错 SimpleXMLElement::addChild(): unterminated entity reference
将 item
中每一项用 htmlspecialchars()
方法转义
<?xml version="1.0" encoding="UTF-8"?>
<rss
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
<channel>
<title>title</title>
<link>http://moell.cn</link>
<description>description</description>
<category domain="http://www.moell.cn">html</category>
<item>
<title>title0</title>
<description>description</description>
<pubDate>Mon, 03 Jan 2022 22:57:08 +0800</pubDate>
<source url="http://www.moell.cn">moell.cn</source>
</item>
<item>
<title>title1</title>
<description>description</description>
<pubDate>Mon, 03 Jan 2022 22:57:08 +0800</pubDate>
<source url="http://www.moell.cn">moell.cn</source>
</item>
</channel>
</rss>
生成rss订阅文件后,将文件地址放到页面header中。
<link rel="alternate" type="application/rss+xml" title="木偶笔记 » RSS 2.0" href="//wangmaolin.net/storage/feed.xml" />
如果您的网站有多个 RSS 订阅源,只需添加多个如上标签即可。
[1]
moell/rss: https://github.com/moell-peng/rss[2]
http://www.rssboard.org/rss-specification: http://www.rssboard.org/rss-specification[3]
RSS 教程参考文档: https://www.runoob.com/rss/rss-tutorial.html