RSS(Really Simple Syndication)订阅源有一种规范的 XML 格式,通常称为 RSS feed。这个规范定义了一种结构化的 XML 文档格式,用于发布网站内容更新的摘要信息,供用户订阅和阅读。
RSS 订阅源的规范格式通常包括以下基本元素:
<channel>
:包含整个 RSS 订阅源的信息,如标题、链接、描述等。<item>
:包含单个内容项的信息,如标题、链接、发布日期、描述等。- 其他元素:如标题、链接、描述、发布日期等,用于描述每个内容项的具体信息。
一、生成 RSS
class RssFeed {
private $channelTitle;
private $channelLink;
private $channelDescription;
private $items;
public function __construct($title, $link, $description) {
$this->channelTitle = $title;
$this->channelLink = $link;
$this->channelDescription = $description;
$this->items = array();}
public function addItem($title, $link, $description, $pubDate) {$this->items[] = array(
"title" => $title,
"link" => $link,
"description" => $description,
"pubDate" => $pubDate
);
}
public function generateFeed()
{header("Content-type: application/xml; charset=utf-8");
$xml = '<?xml version="1.0"encoding="UTF-8"?>';
$xml .= '<rss version="2.0">';
$xml .= '<channel>';
$xml .= '<title>'.$this->channelTitle.'</title>';
$xml .= '<link>'.$this->channelLink.'</link>';
$xml .= '<description>'.$this->channelDescription.'</description>';
$xml .= '<language>en-us</language>';
foreach ($this->items as $item) {
$xml .= '<item>';
$xml .= '<title>'.$item['title'].'</title>';
$xml .= '<link>'.$item['link'].'</link>';
$xml .= '<description>'.$item['description'].'</description>';
$xml .= '<pubDate>'.$item['pubDate'].'</pubDate>';
$xml .= '</item>';
}
$xml .= '</channel>';
$xml .= '</rss>';
echo $xml;
}
}
// 创建 RssFeed 实例
$rss = new RssFeed("Your Channel Title", "http://www.example.com", "Your channel description");
// 添加内容项
$rss->addItem("Item 1 Title", "http://www.example.com/item1", "This is the description of item 1", "Wed, 02 Oct 2021 08:00:00 GMT");
$rss->addItem("Item 2 Title", "http://www.example.com/item2", "This is the description of item 2", "Thu, 03 Oct 2021 08:00:00 GMT");
// 生成并输出 RSS 订阅源
$rss->generateFeed();
二、解析 RSS 订阅源
class RSS {
private $url;
public function __construct($url) {$this->url = $url;}
public function get_feed() {$xml = simplexml_load_file($this->url);
$feed = array('title' => (string) $xml->channel->title,
'description' => (string) $xml->channel->description,
'items' => array(),);
foreach($xml->channel->item as $item) {$feed['items'][] = array('title' => (string) $item->title,
'description' => (string) $item->description,
'link' => (string) $item->link,
'date' => (string) $item->pubDate,
);
}
return $feed;
}
}
$rss = new Rss('https://www.bomx.cn/feed');
var_dump($rss->get_feed());
正文完
有偿技术支持加微信