Close

August 10, 2009

Quick PHP RSS Feeds

Here is a snippet of code that I wish I had when I needed to write a small routine to output a PHP RSS feed.
RSS Feeds are XML-like so they need to be carefully crafted.

1.) Setup the main header of the rss feed. Remember to carefully escape all of your text going into string
fields using htmlentities().

$items = '<?xml version="1.0" encoding="ISO-8859-1" ?> 
	<rss version="2.0"> 
		<channel> 
			<title>Feed Title</title> 
			<link>http://LinkyToThisFeed/rss.xml</link> 
			<description>Our Feed Description</description>';

2.) Now we add some items to the feed. Make sure to escape the string using htmlentities. You do not have to do it in the CDATA encapsulated fields.

 
//You will need to render your dates into an RFC 822 compliant date
//Thankfully PHP already provides us with a built in format type: date(DATE_RSS, $mydate);
$date= date(DATE_RSS, $time());
$title=htmlentities("My Title");
$link="http://linkytoarticle/article1.html";
$blurb="My News Blurb.  I could actually add the whole article if I wanted here";
 
 $items .= '<item> 
	<pubDate>'.$date.'</pubDate>
 
	<title>'. $title .'</title> 
	<link>'. $link .'</link> 
	<description><![CDATA['. $blurb ']]></description> 
		 </item>'; 
 
//rinse, wash, repeat for your items

3.) Don’t forget to close up the tag when you are finished

$items .= '</channel> 
	                </rss>';

Hope this helps!