How to Create an RSS Feed for Your Site in PHP
Most blogging platforms come with built-in support for RSS feeds. Why? It’s a great way for users to keep up to date on your new content. Instead of loading up a dozen favorite sites, they can look at one feed reader and then decide what to pursue further.
So what if you don’t use a blogging platform or CMS that creates a feed for you? You can create one yourself in PHP. It’s pretty simple.
Elements of an RSS 2.0 Feed
There are pretty strict standards about RSS feeds - intended to make it easier for readers to parse and display the information. Before we dive into building a feed, we should look at what it should contain. You can read the full spec at feedvalidator.
An RSS 2.0 Feed is a special type of XML file. The first things you’ll need in your file is an xml declaration, and an opening/closing RSS tag. Like this.
<?xml version="1.0" encoding="utf-8"?> <rss version="2.0"> // Feed elements here </rss>
Inside the opening rss tag, you can also include any namespaces that you’ll be using. That’s a bit more than we need to worry about at the moment, though.
Inside the rss tag, you need to create a channel tag. This holds all of the individual articles as well as some basic information about the feed. You’re required to create a title, link, and description tag. You can add a lot of optional tags, of which the lastBuildDate tag would be most useful.
A basic channel declaration would look something like this.
<channel> <title>My Wonderful Blog</title> <link>http://mydomain.com</link> <description>This is a feed of the latest articles at My Wonderful Blog.</title> <lastBuildDate>Thu, 14 Feb 2008 10:57:05 GMT</lastBuildDate> // Include individual articles here </channel>
Finally, you can include the individual articles inside of this channel tag. Each article is represented by an item tag and a series of optional tags. Some good tags to use for a basic feed would be title, link, description, and pubDate. Like this…
<item> <title>My Latest Article</title> <link>http://mydomain.com/latestarticle.php</link> <description>This is the latest cool article at my wonderful blog.</description> <pubDate>Thu, 14 Feb 2008 10:57:05 GMT</pubDate> </item>
Using PHP to Create the RSS Feed
Now that we know what goes in to an RSS feed, we can worry about how to create one.
There are several approaches we can take here. We could have PHP dynamically output an RSS feed every time the file is accessed. We could create a SimpleXML object and write it to a file each time a new article is added. Or we could simply create a string and write it to an xml file.
We’ll take the third approach. This means we need to do three things.
- Fetch the data from the database
- Build the xml formatted string
- Write the xml data to a file
Fetch the Data from the Database
This will vary depending on the database type you’re using and how it’s set up. If you’ve gotten this far in creating a dynamic, PHP-driven site, I’m sure you can figure out how to fetch information for your own database.
For the purpose of this tutorial, we’ll fetch information from a mySQL database. The database will hold the title, link, description, and pubDate of each article.
$query = "SELECT title, link, description, pubDate FROM articles LIMIT 10"; $result = mysql_query($query);
Note: I only retrieved the last 10 entries. There is no strict limit to the number of entries an RSS 2.0 feed can have, but it’s polite to leave it small. If they want to read every article, they’ll come to your site.
Building the XML Formatted String
Now, we need to create a blank string, format it like an XML file, loop through the mySQL result array, and insert the data into the XML file.
First, we’ll add the xml declaration, the rss tag, the channel tag, and the channel info. Then we can loop through the result set and create one item tag for each article.
$xmlString = '<?xml version="1.0" encoding="utf-8"?> <rss version="2.0"> <channel> <title>My Wonderful Blog</title> <link>http://mydomain.com/</link> <description>Latest articles at My Wonderful Blog.</description> <lastBuildDate>' . date("D, d M Y H:i:s e") . '</lastBuildDate> '; while ($row = mysql_fetch_array($result)) { $xmlString .= ' <item> <title>' . $row['title'] . '</title> <link>' . $row['link'] . '</link> <description>' . $row['description'] . '</description> <pubDate>' . date("D, d M Y H:i:s e", $row['pubDate'] . '</pubDate> </item> '; } $xmlString .= '</channel> </rss>';
Most of that should be self-explanatory. Where I added a newline before ending the string, I was simply adding white space to make the source code more readable. This isn’t necessary - but I like neat, readable source code.
$xmlString is being created in the beginning. Then, the additional strings are appended to it with the .= operator.
The one important thing to note here is date("D, d M Y H:i:s e"). This is PHP’s function to create a formatted date. The characters inside the string determine how the timestamp is formatted.
This format is the standard required by RSS 2.0 feeds. You could simply copy and paste this string to format your dates. “D, d M Y” creates something like “Thu, 14 Feb 2008.” “H:i:s” creates the time as “18:23:30.” “e” is a representation of the timezone - which should be GMT.
Write the String to an XML File
Finally, we need to write this string to an xml file. For simplicity’s sake, we’ll call this “feed.xml” and place it in the same directory as our script.
You could use a few functions to do the file-writing. In this case, file_put_contents would be simplest - all we need to do is dump the contents of the string into a file and overwrite any previous contents.
$filename = "feed.xml"; file_put_contents($filename, $xmlString);
Now you just need to incorporate this into your existing site. You could make this a standalone script and access it every time you add new content to your site.
Or, if you’re using some kind of home-brewed CMS, you could wrap this in a function and call it right after you save the content of a new article.
Besides creating a custom feed for your own website, there are some other uses for this. You could use it to create a feed of articles from diverse sources around the internet.
If you write at a variety of sites - like Helium, Associated Content, and Xomba - you can use this to create a unified feed. Or, you could create a feed of only select articles from one of those sources. You could also create a feed of simple data - not articles - like quotes, jokes, tips, etc.







Pages tagged "tutorial" said this on February 15th, 2008 at 11:43 am
[…] bookmarks tagged tutorial How to Create an Web Cash Feed for Your Site in PH… saved by 5 others mehrwish bookmarked on 02/15/08 | […]
Reza said this on February 17th, 2008 at 1:00 am
It’s a very helpful post for creating rss in php. I like it most. Thanks for the tutorial
Rajaie said this on February 17th, 2008 at 9:33 am
Really simple and great tutorial!
Katalog Stron said this on February 17th, 2008 at 12:22 pm
Simple but usefull!
Lokesh said this on February 21st, 2008 at 6:46 am
Just learning xml with php. awesome tutorial which I understood with no confusions. now can someone help me as to how could I incorporate this on any of the sites. any help would be highly appreciated - Lokesh
RSS Feed: Building an RSS Data Feed in PHP with SimpleXML | Web Cash said this on February 21st, 2008 at 8:48 pm
[…] feeds are a must-have for modern websites. It’s easy enough to make an RSS feed of recent articles in PHP. But did you know an RSS feed can simply be information - not links to […]
Doony said this on March 8th, 2008 at 2:49 pm
If the link contain “&” it will be error. Also with bad character in the description. It should be parsing first.
http://www.avun.com/rss/feed.xml
Walkere said this on March 9th, 2008 at 8:05 am
Never noticed that (I always used pretty URLs instead of ampersands in query strings).
Ampersands aren’t acceptable characters for XML. Usually, ampersands in URLs are ignored, but apparently it breaks most feed readers and stops them from parsing the feed.
Convert them to their html entity form - &. You can do that quickly by using the htmlentities() function on the un-escaped string.
There are still a few validation errors in your feed after that, but it will load properly (in Firefox) if you fix the ampersands.
shialesh said this on March 11th, 2008 at 9:25 pm
hi I Place this code on my website but it give error
http://feedvalidator.org/check.cgi?url=http%3A%2F%2Fwww.dogspot.in%2Fsyndication%2Ffeed.xml
http://www.dogspot.in/syndication/feed.xml
It is taking html tag as error .. can u please tell me how can i correct this
Walkere said this on March 12th, 2008 at 5:30 am
It seems that XML doesn’t like the entity reference . Try taking those references out and replacing them with regular spaces and see if the feed loads then.
Tips to Ensure Your XML RSS Feed is Valid | Web Cash said this on March 15th, 2008 at 9:01 am
[…] month, I wrote on article on creating an RSS feed for your site. Some people have reported problems with the process - but these all come from malformed XML, not […]
Andy said this on April 10th, 2008 at 7:23 am
As RSS come in XML format, things become much simple if using native XML database/XQuery, that allows storing and processing your XML “AS IS”. Take a look at Sedna (www.modis.ispras.ru/sedna), it provides PHP API, very easy to start working with.
Joe said this on August 23rd, 2008 at 7:28 am
You never closed the parentheses for the date() function in your while loop. Probably ends up an error.