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">
<channel>
  <title>digg.com: Stories / Popular</title>
  <language>en-us</language>
  <description>digg.com: Stories / Popular</description>
  <link>http://digg.com/</link>
  <item>
   <title>6 Russian Volcanoes Erupt Simultaneously</title>
   <link>http://feeds.digg.com/~r/digg/popular/~3/ufca-hKu7hM/6_Russian_Volcanoes_Erupt_Simultaneously</link>
   <description>*****</description>
   <pubDate>Wed, 16 Sep 2009 22:30:01 +0000</pubDate>
   <guid isPermaLink="false">http://digg.com/environment/6_Russian_Volcanoes_Erupt_Simultaneously</guid>
  </item>
  <item>
   <title>Happiness: The New Currency in France</title>
   <link>http://feeds.digg.com/~r/digg/popular/~3/7hQDWvQwx5A/Happiness_The_New_Currency_in_France</link>
   <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">http://digg.com/health/Happiness_The_New_Currency_in_France</guid>
  </item>
  <item>
   <title>The 15 Weirdest Music Videos Of All Time</title>
   <link>http://feeds.digg.com/~r/digg/popular/~3/QTH3TyAZma0/The_15_Weirdest_Music_Videos_Of_All_Time</link>
   <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">http://digg.com/music/The_15_Weirdest_Music_Videos_Of_All_Time</guid>
  </item>
</channel>
</rss>

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

$rss = simplexml_load_file("http://feeds.digg.com/digg/popular.rss");

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