PHP: Easy way to parse XML and RSS feeds

With PHP 5, you can use either simplexml_load_file() or simplexml_load_string() to get an instance of the SimpleXMLElement class.

This is a massively simplified feed from Digg. (Shame the example didn't include anything about Kanye West being a big jackass to Taylor Swift)

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <title> Stories / Popular</title>
  <description> Stories / Popular</description>
   <title>6 Russian Volcanoes Erupt Simultaneously</title>
   <pubDate>Wed, 16 Sep 2009 22:30:01 +0000</pubDate>
   <guid isPermaLink="false"></guid>
   <title>Happiness: The New Currency in France</title>
   <description>Gross domestic product, inflation, unemployment- these are old-fashioned, Anglo-Saxon indicators of national wellbeing, says the president of France. From now on, the country's economic progress will be measured in terms of happiness.</description>
   <pubDate>Wed, 16 Sep 2009 22:10:02 +0000</pubDate>
   <guid isPermaLink="false"></guid>
   <title>The 15 Weirdest Music Videos Of All Time</title>
   <description>Music videos changed the music industry completely. Artists were finally given a "visual voice" and fans were able to put faces with names. Musicians are often a little quirky however, resulting in many truly bizarre videos.</description>
   <pubDate>Wed, 16 Sep 2009 22:00:01 +0000</pubDate>
   <guid isPermaLink="false"></guid>

To parse the items in this list, simply use the following.

$rss = simplexml_load_file("");

echo "Parsing feed with title: " . $rss->channel->title;

foreach ($rss->channel->item as $item) {
  echo $item->title;
  echo $item->link;
  echo $item->description;
  echo $item->guid;

And there you have it, very simple.

Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog