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:
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"> <channel> <title>BBC News - Home</title> <link>http://www.bbc.co.uk/news/#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa</link> <description>The latest stories from the Home section of the BBC News web site.</description> <language>en-gb</language> <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> <image> <url>http://news.bbcimg.co.uk/nol/shared/img/bbc_news_120x60.gif</url> <title>BBC News - Home</title> <link>http://www.bbc.co.uk/news/#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa</link> <width>120</width> <height>60</height> </image> <ttl>15</ttl> <atom:link href="http://feeds.bbci.co.uk/news/rss.xml" rel="self" type="application/rss+xml"/> <item> <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> <link>http://www.bbc.co.uk/news/uk-politics-21569997#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa</link> <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"/> </item> </channel> </rss>
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