Is th开发者_开发知识库ere a good PHP Class to generate a RSS file from mysql tables?
There are ready to use classes for building rss feeds like this one found on phpclasses.org but it is just as easy to read up on the rss spec and generate the XML yourself with XMLWriter which is based on libxml and included in PHP5.
When you are actually generating the feeds yourself it never hurts to understand the spec.
I've wrote few hours ago small classes and tested it with feed validator and it work really fine. Here source code
<?php
/**
* Top Level Element or RSS Feed 2.0.
*
* RSS Parent Element.
*
* @version 1.0
* @author makemoney2010
* @property array $Channels array of RSSChannell
*/
class RSS
{
public $Channels=array();
function __construct()
{
$this->Channels=array();
}
/**
* Add a new RSSChannell to the Channells
* @method void
* @param RSSChannell $RssChannell
*/
function addChannell($RssChannell)
{
$this->Channels[]=$RssChannell;
}
/**
* Clear all the item within the channells
* @method void
*/
function clearChannells()
{
$this->Channels=array();
}
/**
* Get full RSS xml
* @param boolean $forceCData Define is Cdata must be used or not this value will be propagated within all child RSSchannels and/or their itemChannell
* @return string Full RSS structure that should be used as response or even as string to put within a static file.
*/
function getOutputXML($forceCData)
{
$output='<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">';
foreach($this as $key=>$value)
{
if (is_array($value))
{
foreach($value as $key => $item)
{
/** @var RSSChannell $item */
$output.= $item->getOutputXML($forceCData);
}
}
//$output.=$value->getOutputXML($forceCData);
}
$output.='</rss>';
return $output;
}
}
/**
* Class Channell
* @property string $title Channell title REQUIRED NOT OPTIONAL IN RSS
* @property string $description Description of the channell REQUIRED NOT OPTIONAL IN RSS
* @property string $atomlink <atom:link href="http://dallas.example.com/rss.xml" rel="self" type="application/rss+xml" />
* @property string $copyright Copyright notice for content in the channel: Example {copyright 2002, Spartanburg Herald-Journal} OPTIONAL NOT REQUIRED IN RSS
* @property string $managingEditor Email address for person responsible for editorial content. Example {geo(et)herald.com (George Matesky)} OPTIONAL NOT REQUIRED IN RSS
* @property string $webMaster Email address for person responsible for technical issues relating to channel. Example {betty(et)herald.com (Betty Guernsey)} OPTIONAL NOT REQUIRED IN RSS
* @property string $language Language of the channell OPTIONAL NOT REQUIRED IN RSS
* @property string $pubDate The publication date for the content in the channel. For example, the New York Times publishes on a daily basis, the publication date flips once every 24 hours. That's when the pubDate of the channel changes. All date-times in RSS conform to the Date and Time Specification of RFC 822, with the exception that the year may be expressed with two characters or four characters (four preferred). Example {Sat, 07 Sep 2002 00:00:01 GMT} OPTIONAL NOT REQUIRED IN RSS
* @property string $lastBuildDate The last time the content of the channel changed. Example {Sat, 07 Sep 2002 09:42:31 GMT} OPTIONAL NOT REQUIRED IN RSS
* @property string $category Specify one or more categories that the channel belongs to. Follows the same rules as the <item>-level category element. OPTIONA NOT REQUIRED IN RSS
* @property string $generator A string indicating the program used to generate the channel. Example {MightyInHouse Content System v2.3}
* @property string $docs A URL that points to the documentation for the format used in the RSS file. It's probably a pointer to this page. It's for people who might stumble across an RSS file on a Web server 25 years from now and wonder what it is. More info at http://blogs.law.harvard.edu/tech/rss OPTIONAL NOT REQUIRED IN RSS
* @property string $cloud Allows processes to register with a cloud to be notified of updates to the channel, implementing a lightweight publish-subscribe protocol for RSS feeds. More info here. <cloud domain="rpc.sys.com" port="80" path="/RPC2" registerProcedure="pingMe" protocol="soap"/> OPTIONAL NOT REQUIRED IN RSS
* @property string $ttl ttl stands for time to live. It's a number of minutes that indicates how long a channel can be cached before refreshing from the source. OPTIONAL NOT REQUIRED IN RSS
* @property string $image Specifies a GIF, JPEG or PNG image that can be displayed with the channel OPTIONAL NOT REQUIRED IN RSS
* @property int $rating The PICS rating for the channel OPTIONAL NOT REQUIRED IN RSS
* @property int $skipHours A hint for aggregators telling them which hours they can skip OPTIONAL NOT REQUIRED IN RSS
* @property int $skipDays A hint for aggregators telling them which days they can skip OPTIONAL NOT REQUIRED IN RSS
* @method getCountItems() Get count of items inclued into array ChannellsItems
*/
class RSSChannell{
#region properties
public $language;
private $channellsItems=array();
public $atomlink;
public $title;
public $description;
public $pubDate;
public $copyright;
public $managingEditor;
public $webMaster;
public $lastBuildDate;
public $category;
public $generator;
public $docs;
public $cloud;
public $ttl;
public $image;
public $rating;
public $skipHours;
public $skipDays;
#endregion
#region void
/**
* Summary of __construct
* @param string $lang setup the channell language and the default array of ItemChannell
* @param array $channellsItems as collection of itemChannell
*/
function __construct($lang)
{
$this->language=$lang;
$this->channellsItems=array();
}
/**
* Clear all the items within the $channellsItems array
* @method void clearChannellItems()
*/
function clearChannellItems()
{
$this->channellsItems=array();
}
/**
* Add a new item to the channellsItems collection
* @method void addItemChannell(itemChannell $itemChannell)
* @param ItemChannell $itemChannell
*/
function addItemChannell($itemChannell)
{
$this->channellsItems[]=$itemChannell;
}
/**
* Set basic Email information within the feed about webmaster, copyright,managingEditor at once.If need it could be changed one by one setting its own right value.
* @param mixed $email
* @param mixed $name
*/
function setBasicEmail($email,$name)
{
$this->copyright=$email.' ('.$name.')';
$this->managingEditor=$email.' ('.$name.')';
$this->webMaster=$email.' ('.$name.')';
}
/**
* Set Email information about copyright.
* @param string $email
* @param string $name
* @method void
*/
function setCopyright($email,$name)
{
$this->copyright=$email.' ('.$name.')';
}
/**
* Set Email information about managingEditor
* @param string $email
* @param string $name
* @method void
*/
function setmanagingEditor($email,$name)
{
$this->managingEditor=$email.' ('.$name.')';
}
/**
* Set basic Email information about webmaster
* @param string $email
* @param string $name
* @method void
*/
function setwebMaster($email,$name)
{
$this->webMaster=$email.' ('.$name.')';
}
#endregion
#region functions
/**
* Return the count of all the items within channellsItems
* @return int
*/
function getCountItems()
{
return count($this->channellsItems);
}
/**
* @method function
* @param boolean $forceCData For default True indicate if use CDATA section within string field in order to prevent wrong markup in RSS feed too
*/
function getOutputXML($forceCData=true)
{
$output='<channel>';
$items='';
foreach($this as $key=>$value)
{
if(is_array($value))
{
$o=new ItemChannell();
foreach($value as $item)
{
/** @var ItemChannell $item */
$items.= $item->getOutputXML($forceCData);
}
}else
{
if(!empty($value) || $value !=null || $value!=0 || $value!='')
{
//cheking for atomlink element
if($key==='atomlink')
{
$output.='<atom:link href="'.$value.'" rel="self" type="application/rss+xml" />';
}
else{
if($forceCData)
{
$value=htmlspecialchars($value);
$output.=sprintf('<%1$s><![CDATA[%2$s]]></%1$s>',$key,$value);
}
else
{
$value=htmlspecialchars($value);
$output.=sprintf('<%1$s>%2$s</%1$s>',$key,$value);
}
}
}
}
}
$output.=$items;
$output.='</channel>';
return $output;
}
#endregion
}
/**
* Class ItemChannel exposes all the properties within a fully compliant RSS item element
* @property string $title The title of the item. Example: Venice Film Festival Tries to Quit Sinking
* @property string $link The URL of the item. Example: http://nytimes.com/2004/12/07FEST.html
* @property string $description Example: The item synopsis.Some of the most heated chatter at the Venice Film Festival this week was about the way that the arrival of the stars at the Palazzo del Cinema was being staged.
* @property string $author Email address of the author of the item.
* @property string $category Includes the item in one or more categories.
* @property string $comments URL of a page for comments relating to the item. Example: http://www.myblog.org/cgi-local/mt/mt-comments.cgi?entry_id=290
* @property string $enclosure Describes a media object that is attached to the item.
* @property string $guid A string that uniquely identifies the item.
* @property datetime $pubDate Indicates when the item was published. Example: Sun, 19 May 2002 15:21:36 GMT
* @property string $source The RSS channel that the item came from.
*/
class ItemChannell{
#region properties
public $title;
public $link;
public $description;
public $author;
public $category;
public $comments;
public $enclosure;
public $guid;
public $pubDate;
public $source;
#endregion
#region void
/**
* Constructor of the Items
*/
function __construct()
{
//Nothing required
}
/**
* Set the title of the item
* @method void
* @param string $title
*/
function setTitle($title)
{
$this->title=$title;
}
/**
* Set the link of the item
* @method void
* @param string $link
*/
function setLink($link)
{
$this->link=$link;
}
/**
* Set the description of the item
* @method void
* @param string $description
*/
function setDescription($description)
{
$this->description=$description;
}
/**
* Set the author of the item
* @method void
* @param string $author
*/
function setAuthor($author)
{
$this->author=$author;
}
/**
* Set the category of the item
* @method void
* @param string $category
*/
function setCategory($category)
{
$this->category=$category;
}
/**
* Set comments url of the item
* @method void
* @param mixed $comments
*/
function setCommentsUrl($comments)
{
$this->comments=$comments;
}
/**
* Set enclosure of item
* @method void
* @param string $enclosure
*/
function setEnclosure($enclosure)
{
$this->enclosure=$enclosure;
}
/**
* Set guid of the item
* @method void
* @param string $guid
*/
function setGuidItem($guid)
{
$this->guid=$guid;
}
/**
* Set pubdate of the item
* @method void
* @param datetime $pubDate
*/
function setPubDate($pubDate)
{
$this->pubDate=$pubDate;
}
/**
* Set source of item
* @method void
* @param string $source
*/
function setSource($source)
{
$this->source=$source;
}
#endregion
#region function
/**
* Get the output in xml format for the rss item
* @method function
* @param boolean $forceCDATA Include all the item of type string within a CDATA section in order to prevent issues.Default use it.
* @return string Xml well formatted as requires
*/
function getOutputXML($forceCDATA=true)
{
$output='<item>';
foreach($this as $key=> $value)
{
if(!empty($value) || $value !=null || $value!=0 || $value!='')
{
if($forceCDATA)
{
$value=htmlspecialchars($value);
$output.=sprintf('<%1$s><![CDATA[%2$s]]></%1$s>',$key,$value);
}
else
{
$output.=sprintf('<%1$s>%2$s</%1$s>',$key,$value);
}
}
}
$output.='</item>';
return $output;
}
#endregion
}
With that file you have complete access to all the classes that you could need to create a complete RSS.
Here below a simple example of the use of those classes
function test()
{
//Define a basic RSS object which represent the root ot the RSS Feed too
$rss= new RSS();
//Declare a RSS Channell object and fill the property that you need here below a simple example
$rssChan= new RSSChannell('en');
$rssChan->title='This is my first Channell RSS';
$rssChan->description='this channell is very cool and is built in a simple manner with a specialized class';
$rssChan->category='Category';
$rssChan->setBasicEmail('domain@domain.com','Jhon Doe');
$rssChan->atomlink='http://domain.com/';
$rssChan->link='http://domain.com/';
//Add the channell to the rss root to
$rss->addChannell($rssChan);
//create a simple iteration in order to create specialized list of ItemChannel whith will be used as item in the RSSChannell above
for ($i = 0; $i < 10; $i++)
{
$rssItem= new ItemChannell();
$rssItem->guid='http://domain.com/'.$i;
$rssItem->setCategory('Category names in this fields '.$i);
$rssItem->setAuthor('jhondoe@domain.com (Jhon Doe)');
$rssItem->setDescription('this is a description item within rss');
//Add each item to the RSSChannell collection
$rssChan->addItemChannell($rssItem);
}
//print output into your page don\'t forget that this is an xml output and so you have to set your header as application/xml.
header('Content-Type: application/xml');
//call RSS root Method getOutputXML($bool) (Take a look into description of all methods properties of the class),
echo $rss->getOutputXML(false);
}
That's all you will have a full RSS feed done. There are more available stuff that could be implemented into the classes but as i need just this have no extened to much this one however you can extend with method to save into a file, append to a file a more other stuff.
I hope this could be a good point to start in order to have a simple way to achieve your goal and make it very easier.
Regards Makemoney2010
You can use XMLDOM. RSS is just XML.
精彩评论