Home >Backend Development >PHP Tutorial >How to implement the function of making xml-based RSS feeds in php
This article mainly introduces the function of PHP to create RSS feeds based on xml, and analyzes the definition and use of RSS feed file generation classes in the form of examples. Friends in need can refer to the examples of this article
Describes the function of using PHP to create RSS feeds based on XML. Share it with everyone for your reference, the details are as follows:
First make an RSS template. The file name of the template is feed.xml, and the code is as follows:
<?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xmlns:wfw="http://wellformedweb.org/CommentAPI/"></rss>
Then use a php file to read data from the database and generate an RSS file. Here, an array is used to simulate the data read from the database:
<?php class Rss{ protected $dom = null; protected $temp = './feed.xml'; protected $rss = null; protected $title = ''; protected $desc = ''; protected $link = ''; public function __construct(){ $this->title = '物理学'; $this->desc = '现代物理学'; $this->link = 'http://mysql/rss.php'; $this->dom = new DOMDocument('1.0','utf-8'); $this->dom->load($this->temp); $this->rss = $this->dom->getElementsByTagName('rss')->item(0); } public function feed($arr){ $this->createChannel(); $channel = $this->dom->getElementsByTagName('channel')->item(0); foreach ($arr as $v){ $channel->appendChild($this->createItem($v)); } header('content-type:text/xml'); echo $this->dom->savexml(); } protected function createChannel(){ $channel = $this->dom->createElement('channel'); $channel->appendChild($this->createEle('title',$this->title)); $channel->appendChild($this->createEle('link',$this->link)); $channel->appendChild($this->createEle('description',$this->desc)); $this->rss->appendChild($channel); } protected function createItem($arr){ $item = $this->dom->createElement('item'); foreach($arr as $k => $v){ $item->appendChild($this->createEle($k,$v)); } return $item; } protected function createEle($name,$value){ $e=$this->dom->createElement($name); $t=$this->dom->createTextNode($value); $e->appendChild($t); return $e; } } $arr = array( array( 'title'=>'牛顿力学', 'link'=>'1', 'description'=>'牛顿力学' ), array( 'title'=>'相对论', 'link'=>'1', 'description'=>'爱因斯坦的相对论' ) ); $rss = new Rss; $rss->feed($arr); ?>
Finally The effect under Firefox:
The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
Related knowledge points about AJAX RSS reader
php Generate RSS file class example code
Code example of using php to read RSS feed
The above is the detailed content of How to implement the function of making xml-based RSS feeds in php. For more information, please follow other related articles on the PHP Chinese website!