Aug/090
RSS Feed Generation with PHP

RSS Logo
I'm sure many of you can relate to my position, with life being a constant party, I don't have time to check my favourite sites every day. From stepping out of supercars to climbing onto private jets, my crazed antics leave no time for browsing for updates. Thankfully with the advent of RSS, I can set up my feed reader to check for updates periodically, saving up to a full minute - and he who owns a machine capable of getting me from 0-60 in 3.4 seconds should not have to wait for a webpage to load. Yet jokes aside, RSS feeds provide a real benefit, for both users and webmasters - it could be considered the web 2.0 newsletter and creates a bond which exceeds beyond a visit to your site.
In this article I provide a solution I make use of on my sites to generate an RSS feed each time a new article is posted, covering each aspect from reading the data off a mysql database to running file operations that create and write the XML file. Read on for a summary of RSS and the steps needed to achieve syndication bliss ...
For those unfamiliar, RSS commonly stands for 'Really Simple Syndication' and is a format that allows you, as a website owner, to provide a web feed that users can subscribe to in order be notified when you add new content. In the usual case, webmasters update the RSS feed with a summary of their latest article, and then checked by RSS readers (such as the popular freeware program FeedDemon) and the new post can then be read by the user in similar fashion to that of a received email. The benefit to users is that they can easily be informed when new content is released on their favourite sites, as it happens. For webmasters, it's a great way of holding onto users and maintaining communication with those interested in your work.
This article is different to most that you will find on this site in that it does require a fair bit of experience with PHP and MySQL to fully understand what's going on. To cover the scope of the task in full requires that I summarise and provide this as more of a reference as opposed to detailed instruction. So let's get cracking with the task at hand:
Grabbing the Data From The Database
This step will vary depending on how you have your data stored in the table but the idea is simple, we want to grab the required pieces of data that we will use in the RSS feed. Each 'entry' in our RSS feed (which will correspond for each new article), will have a title, description and link tag - with the latter being a link to the full article and the description serving as an excerpt to entice the reader to read more. So assuming you have your database table set up and that it contains entries, let's read the lastest 10 articles, create an RSS 'item' entry for each, being sure to create the snippet and link as we go along:
$grabDataQuery = "SELECT title, article FROM articles ORDER BY date_added DESC LIMIT 10"; $grabDataResult = mysql_query($grabDataQuery); while($row = mysql_fetch_array($grabDataResult)) { extract($row); $xmlEntries .= '<item>\n'; $xmlEntries .= "<title>$title</title>\n"; // Get first 300 characters of article to use as snippet $snippet = substr($article, 0, 200); $xmlEntries .= "<description>$snippet</description>\n"; // Create the SEO friendly link which is the title hyphenated $pageLink = str_replace(' ', '-', $topic_title); $xmlEntries .= "<link>http://whoneedsactions.com/$pageLink</link>"; $xmlEntries .= "</item>\n"; }
The '\n' is used here to create a new line, helping to keep our RSS source code looking pretty and do note the fact that we are using the concatenation operator '.=' to append to the exsisting variable as oppose to overwriting with each loop. Now with each entry of the RSS feed created, the next step is to prepare to top and bottom of the RSS feed file then write it to a file that our site users can access.
Creating the RSS File
RSS feeds are specified in XML and the format is flexible yet it is required that a standard is followed. The structure of an RSS feed consists of a header (where the feed title and rss version number is noted for example), followed by an 'item' code block for each entry of the feed.The following is a valid example of the opening to an RSS file, with only the required elements, you will of course replace the data with your own sites title, description and URL. Here we set the data to a php variable, which we will then merge with the RSS body created above and the bottom of our file to create our RSS page:
$xmlTop = '<?xml version="1.0"?> <rss version="2.0"> <channel> <title>WhoNeedsActions Latest Articles</title> <descripton>Software and Web Development articles</description> <link>http://www.whoneedsactions.com</link>';
The bottom of the RSS file is simply closing the opened tags to be sure the file will validate. We then merge the top, middle and bottom so we have our full RSS page as on variable, ready to write to file:
$xmlBottom = ' </channel> </rss>'; // Merge all sections of our RSS File $xmlPage = $xmlTop . $xmlEntries . $xmlBottom;
The final step is write to the XML specified file and this is done with ease thanks to the file operation functions that PHP provides. The follow code demonstrates the steps:
// Open file in write mode $handle = fopen($xmlFile, "w+"); // Write the data to file $numbytes = fwrite($handle, $xmlpage); // Then close the file and free the resource $closefile = fclose($handle);
So there we have it, an RSS feed ready to share with the world. An example of a feed created using code almost exactly as shown here is my Eminem News Feed, a quick comparison to the Feed For This Blog shows the variation in options available to you, with the latter being wordpress generated and making use of more available elements for each entry. Ideally you want your RSS feed to be updated automatically every time an article is added to the database, an easy step if this case is wrapped up as a function and called each time such an event takes place.
Any problems or questions, leave a comment - now time to get back to that party.