RSS 2.0: Parsing the New Standard for Content Syndication
It is 2004, and the "Blogosphere" is exploding. Everyone is using RSS (Really Simple Syndication) to keep up with their favorite sites without having to visit them manually. While there are competing formats like Atom, RSS 2.0 (released by Dave Winer) has become the dominant standard.
If you are a PHP developer, 2004 is also exciting because of the release of PHP 5.0. It includes a revolutionary new extension called SimpleXML, which makes parsing XML files-like RSS feeds-as easy as accessing an object.
The RSS 2.0 Structure
An RSS feed is just an XML file with a specific structure. The root is <rss>, followed by a <channel>, which contains many <item> elements.
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>My Awesome Blog</title>
<link>http://example.com/</link>
<item>
<title>Entry One</title>
<link>http://example.com/1</link>
<description>This is the first entry.</description>
<pubDate>Wed, 15 Dec 2004 12:00:00 GMT</pubDate>
</item>
</channel>
</rss>
Parsing with PHP 5's SimpleXML
In PHP 4, we had to use complex SAX or DOM parsers. In PHP 5, it's a one-liner.
<?php
// Load the RSS feed
$rss = simplexml_load_file('http://example.com/rss.xml');
echo "<h1>" . $rss->channel->title . "</h1>";
// Loop through each item
foreach ($rss->channel->item as $item) {
echo "<div>";
echo "<h3><a href='{$item->link}'>{$item->title}</a></h3>";
echo "<p><i>{$item->pubDate}</i></p>";
echo "<p>{$item->description}</p>";
echo "</div><hr>";
}
?>
Handling Namespaces
Some feeds use namespaces (like MediaRSS or Content encoded). SimpleXML handles these with the children() method.
// If the feed has <content:encoded>
$content = $item->children('http://purl.org/rss/1.0/modules/content/');
echo (string)$content->encoded;
The combination of RSS 2.0 and PHP 5 is making the web more interconnected than ever. We're moving from a "destination web" to a "syndicated web," where content finds the user.
Aunimeda develops websites and web applications for businesses - corporate sites, e-commerce, portals, and custom platforms.
Contact us to discuss your web project. See also: Web Development, E-commerce Development