skip to content

PHP: RSS Feed Reader Code Example

 Tweet Share0 Tweets

This page provides some sample code based on our RSS and Atom Feed Reader PHP classes. The HTML generated by this example is the BBC News RSS feed displayed belown on the right hand side of the page.

BBC News - Home

Mexico earthquake: Race to save children under collapsed school
Rescuers step up efforts to find people trapped under rubble, including at a school in Mexico City.
22 September 2017, 1:51am

North Korea says Trump speech is 'a dog's bark'
North Korea's top diplomat was responding to the US president's vow to "totally destroy" the country.
21 September 2017, 6:54pm

© {Copyright: (C) British Broadcasting Corporation, see news.bbc.co.uk/2/hi/help/rss/4498287.stm for terms and conditions of reuse.}

Displaying an external RSS feed as HTML

The PHP class presented in the preceding article also includes a display option, but usually you will want to customise that for your website. In this case we use the 'raw' data to present a list of headlines and dates.

We're using BBC News for this example simply because they have some of the friendliest Terms of Use. Before including any external feeds on your website, always check the relevant Terms of Use to make sure that you're allowed to display their content.

PHP code for this example

Again, this is just an example of what you can do using our PHP classes (there's also code for an Atom Feed Reader) to include external feeds.

The parameters at the top define the feed source, how many items to display and where and for how long to keep a local cached version of the data.

After that it's just a matter of extracting the relevant data from the array returned by getRawOutput() and adding some simple HTML formatting.

<?PHP // define script parameters $BLOGURL = "http://feeds.bbci.co.uk/news/rss.xml?edition=int"; $NUMITEMS = 2; $TIMEFORMAT = "j F Y, g:ia"; $CACHEFILE = "/tmp/" . md5($BLOGURL); $CACHETIME = 4; // hours // download the feed iff a cached version is missing or too old if(!file_exists($CACHEFILE) || ((time() - filemtime($CACHEFILE)) > 3600 * $CACHETIME)) { if($feed_contents = http_get_contents($BLOGURL)) { // write feed contents to cache file $fp = fopen($CACHEFILE, 'w'); fwrite($fp, $feed_contents); fclose($fp); } } include "rssparser.php"; $rss_parser = new RSSParser($CACHEFILE); // read feed data from cache file $feeddata = $rss_parser->getRawOutput(); extract($feeddata['RSS']['CHANNEL'][0], EXTR_PREFIX_ALL, 'rss'); // display leading image if(isset($rss_IMAGE[0]) && $rss_IMAGE[0]) { extract($rss_IMAGE[0], EXTR_PREFIX_ALL, 'img'); echo "<p><a title=\"{$img_TITLE}\" href=\"{$img_LINK}\"><img src=\"{$img_URL}\" alt=\"\"></a></p>\n"; } // display feed title echo "<h4><a title=\"",htmlspecialchars($rss_DESCRIPTION),"\" href=\"{$rss_LINK}\" target=\"_blank\">"; echo htmlspecialchars($rss_TITLE); echo "</a></h4>\n"; // display feed items $count = 0; foreach($rss_ITEM as $itemdata) { echo "<p><b><a href=\"{$itemdata['LINK']}\" target=\"_blank\">"; echo htmlspecialchars(stripslashes($itemdata['TITLE'])); echo "</a></b><br>\n"; echo htmlspecialchars(stripslashes($itemdata['DESCRIPTION'])),"<br>\n"; echo "<i>",date($TIMEFORMAT, strtotime($itemdata['PUBDATE'])),"</i></p>\n\n"; if(++$count >= $NUMITEMS) break; } // display copyright information echo "<p><small>&copy; {",htmlspecialchars($rss_COPYRIGHT),"}</small></p>\n"; ?>

expand code box

As you can see from the code comments, this snippet displays first the image associated with the feed (as a link) followed by the feed title and a limited number of items. At the bottom it displays also the copyright information. Not all RSS/Atom feeds will contain the same items so you may need to customise what is displayed.

Please Note: this code is provided for explanatory purposes only and care should be taken when using or modifying it for any other purpose.

RSSParser: Could not open $file for input

We now use cURL instead of fopen to fetch the RSS feed, so the following is no longer relevant.

This code assumes that the script has permission to create files in the /tmp/ directory and that those files will remain there, readable, for a number of hours. This is so that the RSS feed doesn't have to be fetched again every time the page is loaded, but rather the relevant data can be stored on the server.

If the /tmp/ directory does not exist, is not writable or is not keeping files in place for sufficient time then you will need to create your own webserver-writable directory and change the $CACHEFILE setting accordingly.

To see the actual error message from the server, you will need to change this line in the class file:

$fp = @fopen($file, 'r') or die("RSSParser: Could not open $file for input");

to just:

$fp = fopen($file, 'r');

If there is a problem reading the cache file (and you are not surpressing PHP errors) you should see a number of warning messages. Normally the first line will indicate the actual problem.

Analyzing the Feed data

Using different feed sources can be tricky as they can use different RSS formats which means different tagnames and data formats. The first step then is to examine the 'raw' data to see what tags are available and how they are nested.

<pre><?PHP print_r($feeddata); ?></pre>

The output should be something like the following PHP array. You can see from this how the preceding code extracts data to present the IMAGE, TITLE, ITEMs and COPYRIGHT for the example.

Array ( [TITLE] => BBC News - Home [DESCRIPTION] => BBC News - Home [LINK] => http://www.bbc.co.uk/news/ [IMAGE] => Array ( [0] => Array ( [URL] => http://news.bbcimg.co.uk/nol/shared/img/bbc_news_120x60.gif [TITLE] => BBC News - Home [LINK] => http://www.bbc.co.uk/news/ ) ) [GENERATOR] => RSS for Node [LASTBUILDDATE] => Thu, 21 Sep 2017 16:24:14 GMT [COPYRIGHT] => Copyright: (C) British Broadcasting Corporation, see http://news.bbc.co.uk/2/hi/help/rss/4498287.stm for terms and conditions of reuse. [LANGUAGE] => en-gb [TTL] => 15 [ITEM] => Array ( [0] => Array ( [TITLE] => Mexico earthquake: Race to save children under collapsed school [DESCRIPTION] => Rescuers step up efforts to find people trapped under rubble, including at a school in Mexico City. [LINK] => http://www.bbc.co.uk/news/world-latin-america-41343244 [GUID] => http://www.bbc.co.uk/news/world-latin-america-41343244 [PUBDATE] => Thu, 21 Sep 2017 15:51:03 GMT ) [1] => Array ( [TITLE] => North Korea says Trump speech is 'a dog's bark' [DESCRIPTION] => North Korea's top diplomat was responding to the US president's vow to \"totally destroy\" the country. [LINK] => http://www.bbc.co.uk/news/world-asia-41343646 [GUID] => http://www.bbc.co.uk/news/world-asia-41343646 [PUBDATE] => Thu, 21 Sep 2017 08:54:25 GMT ) ) )

expand code box

If this all seems too complicated you can always go back to the generic HTML display code provided with the PHP classes linked below.

Possible improvements

One drawback of the above script is that every $CACHETIME hours one visitor to the page displaying the RSS feed will have the page load delayed as the feed is updated.

This could be avoided if there was a CRON job (scheduled server side script) updating the $CACHEFILE at regular intervals so you don't have to rely on the PHP script to perform that function.

If that's not an option you can also modify the script so that the fetching of the feed happens at the end of the page rather than in the middle.

To achieve that, we take the section of the code that updates the feed and turn it into a PHP function:

function updateFeed() { global $BLOGURL, $CACHEFILE; if($feed_contents = http_get_contents($BLOGURL)) { // write feed contents to cache file $fp = fopen($CACHEFILE, 'w'); fwrite($fp, $feed_contents); fclose($fp); } }

The code at the top of the script would then read:

// download the feed iff cached version is missing if(!file_exists($CACHEFILE)) updateFeed();

And you can add at the bottom of the page - after all HTML content has been output:

<?PHP // download the feed iff cached version is too old if((time() - filemtime($CACHEFILE)) > 3600 * $CACHETIME) { flush(); updateFeed(); } ?>

These changes will be more useful on a high-traffic website. Otherwise if you only have a couple of visitors a day they will often not see the latest items from the RSS feed unless it's updated before being displayed.

< PHP

Send a message to The Art of Web:


used only for us to reply, and to display your gravatar.

<- copy the digits from the image into this box

press <Esc> or click outside this box to close

User Comments

Post your comment or question

8 July, 2010

The Code Example wasnt working well when the feed contain image in it news. It displays image link instead the image it self. Do you have any idea?

The RSS syntax doesn't allow for images with individual feed items - only for the feed itself. What it does allow for is a file attachment ('ENCLOSURE') - which can be an image or any other type of file.

Our RSS parsing script by default shows any file attachment as just a link with a filetype and file size in bytes. If you want to instead display the image then you need to edit that section the display_item() function.

top