Easy XML and RSS integration in PHP

This post shows how to get XML and/or RSS data from external sites to our site using PHP.
Using this method we could integrate various PHP based CMS's like Drupal, Joomla, Wordpress with external XML feeds.

Getting external RSS feeds

Now consider for example, that you want to get the first two news items from the BBC RSS news feed.
You can do this very easily and quickly using the following piece of code:

$xml = simplexml_load_file('http://feeds.bbci.co.uk/news/rss.xml');
echo "Title: " . $xml->channel[0]->item[0]->title . "<br/>";
echo "Description: " . $xml->channel[0]->item[0]->description . "<br/>";
echo "Title: " . $xml->channel[0]->item[1]->title . "<br/>";
echo "Description: " . $xml->channel[0]->item[1]->description . "<br/>";

The example above assumes the following XML format:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet title="XSL_formatting" type="text/xsl" href="/shared/bsp/xsl/rss/nolsol.xsl"?>

<rss xmlns:media="http://search.yahoo.com/mrss/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">  
    <title>BBC News - Home</title>  
    <description>The latest stories from the Home section of the BBC News web site.</description>  
    <lastBuildDate>Mon, 25 Feb 2013 09:28:11 GMT</lastBuildDate>  
    <copyright>Copyright: (C) British Broadcasting Corporation, see http://news.bbc.co.uk/2/hi/help/rss/4498287.stm for terms and conditions of reuse.</copyright>  
      <title>BBC News - Home</title>  
    <atom:link href="http://feeds.bbci.co.uk/news/rss.xml" rel="self" type="application/rss+xml"/>  
      <title>Lib Dems 'screwed up' over Rennard</title>  
      <description>The Lib Dems' handling of alleged inappropriate behaviour by their former chief executive Lord Rennard is criticised as leader Nick Clegg denies a cover-up.</description>  
      <guid isPermaLink="false">http://www.bbc.co.uk/news/uk-politics-21569997</guid>  
      <pubDate>Mon, 25 Feb 2013 09:29:15 GMT</pubDate>  
      <media:thumbnail width="66" height="49" url="http://news.bbcimg.co.uk/media/images/66050000/jpg/_66050779_66013748.jpg"/>  
      <media:thumbnail width="144" height="81" url="http://news.bbcimg.co.uk/media/images/66050000/jpg/_66050780_66013748.jpg"/> 

You can of course use whatever RSS news source, or whatever XML output in order to get the required data.

Local file

You can as well use the same method for getting data from a local XML file:
$xml = simplexml_load_file('example.xml');

No comments:

Post a Comment