Creating RSS 2.0 Feeds
(Page 1 of 4 )
In this conclusion to a three-part series on the RSS 2.0 specification, you'll learn how to create an RSS feed in several different ways. This article is excerpted from chapter four of the book Developing Feeds with RSS and Atom, written by Ben Hammersley (O'Reilly; ISBN: 0596008813). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
RSS 0.91 and 0.92 feeds are created in the same way; the additional elements found in 0.92 are well-handled by the existing RSS tools.
Of course, you can always hand-code your RSS feed. Doing so certainly gets you on top of the standard, but it's neither convenient, quick, nor recommended.
There are various ways to create a feed, all of which are used in real life:
An RSS-specific module or class within a scripting language
We'll look at all three methods, but let's start with the third, using an RSS-specific module. In this case, it's Perl's XML::RSS.
Creating RSS with Perl Using XML::RSS
The XML::RSS module is one of the key tools in the Perl RSS world. It is built on top of XML::Parser--the basis for many Perl XML modules--and is object-oriented. Actually, XML::RSS also supports the creation of the older versions of RSS, plus RSS 1.0, and it can parse existing feeds, but in this section we will deal only with its 2.0 creation capabilities.
Incidentally, XML::RSS is an open source project. You can lend a hand, and grab the latest version, at http://sourceforge.net/projects/perl-rss.
Examples 4-8 and 4-9 show a simple Perl script and the feed it creates.
Example 4-8. A sample XML::RSS script
my $rss = new XML::RSS( version => '2.0' );
Example 4-9. The resultant RSS 2.0 feed
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:blogChannel="http://backend.userland.com/ blogChannelModule">
After the required Perl module declaration, you create a new instance of XML::RSS, like so:
my $rss = new XML::RSS (version => '2.0');
The new method function returns a reference to the new XML::RSS object. The function can take three arguments, two of which are of interest here:
new XML::RSS (version=>$version, encoding=>$encoding);
The version attribute refers to the version of RSS you want to make (either '2.0' or '1.0', or, if you fancy being a bit retro, '0.91'), and the encoding attribute sets the encoding of the XML declaration. The default encoding, as with XML, is UTF-8.
The rest of the script is quite self-explanatory. The methods channel, image, textinput, and add_item all add new elements and associated values to the feed you are creating, and the print $rss->as_string; prints out the result. You can also call the $rss->save method to save the created feed as a file.blog comments powered by Disqus