skip to content

PHP: RSS Feed Reader Code Example

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

'A hard day' - Ashley Judd on overturned Weinstein conviction
The actress tells BBC News survivors feel betrayed after a new rape trial is ordered for Harvey Weinstein.
26 April 2024, 10:50am

First personalised skin-cancer vaccine starts UK trial
Steve Young is part of the tests to see if an mRNA jab can stop the deadliest skin cancer returning.
26 April 2024, 11:27am

© {Copyright: (C) British Broadcasting Corporation, see www.bbc.co.uk/usingthebbc/terms-of-use/#15metadataandrssfeeds 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 = "https://feeds.bbci.co.uk/news/rss.xml?edition=int"; $NUMITEMS = 2; $TIMEFORMAT = "j F Y, g:ia"; $CACHEFILE = sys_get_temp_dir() . "/" . 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"; $count = 0; // display feed items 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 [DESCRIPTION] => BBC News - News Front Page [LINK] => https://www.bbc.co.uk/news [IMAGE] => Array ( [0] => Array ( [URL] => https://news.bbcimg.co.uk/nol/shared/img/bbc_news_120x60.gif [TITLE] => BBC News [LINK] => https://www.bbc.co.uk/news ) ) [GENERATOR] => RSS for Node [LASTBUILDDATE] => Fri, 26 Apr 2024 06:00:38 GMT [COPYRIGHT] => Copyright: (C) British Broadcasting Corporation, see https://www.bbc.co.uk/usingthebbc/terms-of-use/#15metadataandrssfeeds for terms and conditions of reuse. [LANGUAGE] => en-gb [TTL] => 15 [ITEM] => Array ( [0] => Array ( [TITLE] => 'A hard day' - Ashley Judd on overturned Weinstein conviction [DESCRIPTION] => The actress tells BBC News survivors feel betrayed after a new rape trial is ordered for Harvey Weinstein. [LINK] => https://www.bbc.co.uk/news/world-us-canada-68901032 [GUID] => https://www.bbc.co.uk/news/world-us-canada-68901032#0 [PUBDATE] => Fri, 26 Apr 2024 00:50:26 GMT ) [1] => Array ( [TITLE] => First personalised skin-cancer vaccine starts UK trial [DESCRIPTION] => Steve Young is part of the tests to see if an mRNA jab can stop the deadliest skin cancer returning. [LINK] => https://www.bbc.co.uk/news/health-68897731 [GUID] => https://www.bbc.co.uk/news/health-68897731#0 [PUBDATE] => Fri, 26 Apr 2024 01:27:39 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

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