skip navigation

PHP: RSS Feed Reader: Source Code

This page presents a simple class with a constructor and two public functions: getOutput returns an HTML-formatted version of the RSS feed, while getRawOutput returns all the attributes in a single multi-level array.

<?PHP include "class.myrssparser.php"; // where is the feed located? $url = "http://www.example.net/rss.xml"; // create object to hold data and display output $rss_parser = new myRSSParser($url); $output = $rss_parser->getOutput(); // returns string containing HTML echo $output; ?>

Yes, it really can be that simple.

Source code of class.myrssparser.php

This class is by no means the be-all and end-all of RSS parsing. It's designed to be simple, functional and easily customisable. It appears to work for all RSS formats, and can be extended to handle new formats - or perhaps further to handle general XML parsing.

File: class.myrssparser.php

<?PHP   // Original PHP code by Chirp Internet: www.chirp.com.au   // Please acknowledge use of this code by including this header.   class myRSSParser   {     // keeps track of current and preceding elements     var $tags = array();     // array containing all feed data     var $output = array();     // return value for display functions     var $retval "";     // constructor for new object     function myRSSParser($file)     {       // instantiate xml-parser and assign event handlers       $xml_parser xml_parser_create("");       xml_set_object($xml_parser$this);       xml_set_element_handler($xml_parser"startElement""endElement");       xml_set_character_data_handler($xml_parser"parseData");       // open file for reading and send data to xml-parser       $fp = @fopen($file'r') or die("myRSSParser: Could not open $file for input");       while($data fread($fp4096)) {         xml_parse($xml_parser$datafeof($fp)) or die(           sprintf("myRSSParser: Error <b>%s</b> at line <b>%d</b><br>",           xml_error_string(xml_get_error_code($xml_parser)),           xml_get_current_line_number($xml_parser))         );       }       fclose($fp);       // dismiss xml parser       xml_parser_free($xml_parser);     }     function startElement($parser$tagname$attrs=array())     {       // RSS 2.0 - ENCLOSURE       if($tagname == "ENCLOSURE" && $attrs) {         $this->startElement($parser"ENCLOSURE");         foreach($attrs as $attr => $attrval) {           $this->startElement($parser$attr);           $this->parseData($parser$attrval);           $this->endElement($parser$attr);         }         $this->endElement($parser"ENCLOSURE");       }       // Yahoo! Media RSS - images       if($tagname == "MEDIA:CONTENT" && $attrs['URL'] && $attrs['MEDIUM'] == 'image') {         $this->startElement($parser"IMAGE");         $this->parseData($parser$attrs['URL']);         $this->endElement($parser"IMAGE");       }       // check if this element can contain others - list may be edited       if(preg_match("/^(RDF|RSS|CHANNEL|IMAGE|ITEM)/"$tagname)) {         if($this->tags) {           $depth count($this->tags);           list($parent$num) = each($tmp end($this->tags));           if($parent$this->tags[$depth-1][$parent][$tagname]++;         }         array_push($this->tags, array($tagname => array()));       } else {         if(!preg_match("/^(A|B|I)$/"$tagname)) {           // add tag to tags array           array_push($this->tags$tagname);         }       }     }     function endElement($parser$tagname)     {       if(!preg_match("/^(A|B|I)$/"$tagname)) {         // remove tag from tags array         array_pop($this->tags);       }     }     function parseData($parser$data)     {       // return if data contains no text       if(!trim($data)) return;       $evalcode "\$this->output";       foreach($this->tags as $tag) {         if(is_array($tag)) {           list($tagname$indexes) = each($tag);           $evalcode .= "[\"$tagname\"]";           if(${$tagname}) $evalcode .= "[" . (${$tagname} - 1) . "]";           if($indexesextract($indexes);         } else {           if(preg_match("/^([A-Z]+):([A-Z]+)$/"$tag$matches)) {             $evalcode .= "[\"$matches[1]\"][\"$matches[2]\"]";           } else {             $evalcode .= "[\"$tag\"]";           }         }       }       eval("$evalcode = $evalcode . '" addslashes($data) . "';");     }     // display a single channel as HTML     function display_channel($data$limit)     {       extract($data);       if($IMAGE) {         // display channel image(s)         foreach($IMAGE as $image$this->display_image($image);       }       if($TITLE) {         // display channel information         $this->retval .= "<h1>";         if($LINK$this->retval .= "<a href=\"$LINK\" target=\"_blank\">";         $this->retval .= stripslashes($TITLE);         if($LINK$this->retval .= "</a>";         $this->retval .= "</h1>\n";         if($DESCRIPTION$this->retval .= "<p>$DESCRIPTION</p>\n\n";         $tmp = array();         if($PUBDATE$tmp[] = "<small>Published: $PUBDATE</small>";         if($COPYRIGHT$tmp[] = "<small>Copyright: $COPYRIGHT</small>";         if($tmp$this->retval .= "<p>" implode("<br>\n"$tmp) . "</p>\n\n";         $this->retval .= "<div class=\"divider\"><!-- --></div>\n\n";       }       if($ITEM) {         // display channel item(s)         foreach($ITEM as $item) {           $this->display_item($item"CHANNEL");           if(is_int($limit) && --$limit <= 0) break;         }       }     }     // display a single image as HTML     function display_image($data$parent="")     {       extract($data);       if(!$URL) return;       $this->retval .= "<p>";       if($LINK$this->retval .= "<a href=\"$LINK\" target=\"_blank\">";       $this->retval .= "<img src=\"$URL\"";       if($WIDTH && $HEIGHT$this->retval .= " width=\"$WIDTH\" height=\"$HEIGHT\"";       $this->retval .= " border=\"0\" alt=\"$TITLE\">";       if($LINK$this->retval .= "</a>";       $this->retval .= "</p>\n\n";     }     // display a single item as HTML     function display_item($data$parent)     {       extract($data);       if(!$TITLE) return;       $this->retval .=  "<p><b>";       if($LINK$this->retval .=  "<a href=\"$LINK\" target=\"_blank\">";       $this->retval .= stripslashes($TITLE);       if($LINK$this->retval .= "</a>";       $this->retval .=  "</b>";       if(!$PUBDATE && $DC["DATE"]) $PUBDATE $DC["DATE"];       if($PUBDATE$this->retval .= " <small>($PUBDATE)</small>";       $this->retval .=  "</p>\n";       // use feed-formatted HTML if provided       if($CONTENT['ENCODED']) {         $this->retval .= "<p>" stripslashes($CONTENT['ENCODED']) . "</p>\n";       } elseif($DESCRIPTION) {         if($IMAGE) {           foreach($IMAGE as $IMG$this->retval .= "<img src=\"$IMG\">\n";         }         $this->retval .=  "<p>" stripslashes($DESCRIPTION) . "</p>\n\n";       }       // RSS 2.0 - ENCLOSURE       if($ENCLOSURE) {         $this->retval .= "<p><small><b>Media:</b> <a href=\"{$ENCLOSURE['URL']}\">";         $this->retval .= $ENCLOSURE['TYPE'];         $this->retval .= "</a> ({$ENCLOSURE['LENGTH']} bytes)</small></p>\n\n";       }       if($COMMENTS) {         $this->retval .= "<p style=\"text-align: right;\"><small>";         $this->retval .= "<a href=\"$COMMENTS\">Comments</a>";         $this->retval .= "</small></p>\n\n";       }     }     function fixEncoding(&$input$key$output_encoding)     {       if(!function_exists('mb_detect_encoding')) return $input;       $encoding mb_detect_encoding($input);       switch($encoding)       {         case 'ASCII':         case $output_encoding:           break;         case '':           $input mb_convert_encoding($input$output_encoding);           break;         default:           $input mb_convert_encoding($input$output_encoding$encoding);           break;       }     }     // display entire feed as HTML     function getOutput($limit=false$output_encoding='UTF-8')     {       $this->retval "";       $start_tag key($this->output);       switch($start_tag)       {         case "RSS":           // new format - channel contains all           foreach($this->output[$start_tag]["CHANNEL"] as $channel) {             $this->display_channel($channel$limit);           }           break;         case "RDF:RDF":           // old format - channel and items are separate           if(isset($this->output[$start_tag]['IMAGE'])) {             foreach($this->output[$start_tag]['IMAGE'] as $image) {               $this->display_image($image);             }           }           foreach($this->output[$start_tag]['CHANNEL'] as $channel) {             $this->display_channel($channel$limit);           }           foreach($this->output[$start_tag]['ITEM'] as $item) {             $this->display_item($item$start_tag);           }           break;         case "HTML":           die("Error: cannot parse HTML document as RSS");         default:           die("Error: unrecognized start tag '$start_tag' in getOutput()");       }       if($this->retval && is_array($this->retval)) {         array_walk_recursive($this->retval'myRSSParser::fixEncoding'$output_encoding);       }       return $this->retval;     }     // return raw data as array     function getRawOutput($output_encoding='UTF-8')     {       array_walk_recursive($this->output'myRSSParser::fixEncoding'$output_encoding);       return $this->output;     }   } ?>

expand code box

The parsing of the RSS feed into a PHP array is done by the myRSSParser class using the startElement, endElement and parseData functions. The remaining functions are used only for displaying the data or accessing the raw data.

Here you can copy the code for class.myrssparser.php:

Fields Supported by Default

This script supports the following attributes (fields) by default but can easily be extended. See the Feed Reader Demonstration for examples of parsed RSS (and Atom) feeds.

Channel (RSS or RDF:RDF)

  • Image: URL (required), Width, Height
  • Title
  • Link
  • Description
  • Pubdate
  • Copyright

Item

  • Title (required)
  • Link
  • Pubdate or DC.Date
  • Content->Encoded or Description
  • Enclosure: URL, Type, Length (for multimedia attachments)
  • Comments

If you think it's worth adding support for other RSS attributes, please let us know using the Feedback link below.

Multibyte String Function support

If your PHP install doesn't include Multibyte String Function support then you will see some errors. You can get around that by jettisoning the fixEncoding function.

In other words, replacing:

return $this->fixEncoding($this->retval, $output_encoding);

with just:

return $this->retval;

The feed will then be displayed using it's original character encoding, which may or may not match the encoding of your HTML page, but other than that shouldn't be a problem.

Related Articles

References

< PHP


User Comments and Notes

Akash Takyar 14 January, 2006

Excellent thats what I was looking for. Thanks

jf 13 November, 2006

your source code is very badly formatted when i try to cut and paste it into my php editor - carriage returns are missing, so i have to manually edit the code into order to make it readable.

could you kindly add an option to download the source code instead?

I suggest you try using a different browser when copying, or check whether your editor supports UNIX/Mac<->Windows line break conversion, but stay tuned as well for a download option.

Abhijith Babu 11 December, 2006

Wonderfull, great job...
Great One.
Cheers.

Roozbeh 2 September, 2007

Thank You! This awesome; just what I needed.

Ben 16 September, 2007

I changed the 'fopen or die' do be 'fopen; if fp;' because I found that when the feed I was including timed out, my entire front page was die()ing.

What I normally do is have two scripts - script #1 regularly downloads the RSS Feed and caches the content and script #2 displays the feed using the cached file. That way if the feed source becomes unavailable your page doesn't die()

Brent 6 December, 2007

I get the following:
Fatal error: Call to undefined function: mb_detect_encoding()

That means that Multibyte String Function support hasn't been included in your PHP install. If you remove the fixEncoding function and calls from the PHP script then you can avoid those problems, but you then have to accept the original encoding of the RSS feed.

Shailesh Gajjar 22 February, 2008

I am using the RSS Class but i am getting the problem when i use this RSS URL - www.example.net/atom.xml
Thanks, Shailesh Gajjar

There are two types of feed - RSS and Atom - and we have different classes for each of them. It looks like your feed is in Atom format so you should be using the Atom Feed Reader.

eviriyanti 15 September, 2008

Thanks for this article, its really help me.
(^_^)

joe w 19 March, 2009

this is an excellent tutorial. i searched high and low for an rss tutorial and this one is miles ahead of the others. thank you very much for it. i would like to ask, how do you limit the results per page?

Hi Joe, you just need to pass the number of items you want to display as the first argument to the getOutput() function.

Keith Chadwick 27 March, 2009

I have no display whatso ever!!!!
the only error I receive is
myRSSParser: Could not open www.example.net/rss.xml for input.
I just cannot work out what the problem is - It is not just this example but at least two other reader example also. Any ideas?

Hi Keith, it sounds like your webserver is denying access to the request from PHP. That can happen for example if you have a firewall or filtering rules (mod_rewrite) that deny access when there is no HTTP_USER_AGENT. Check your server logs for a 403 error.

Ben 10 June, 2009

Using blogger's atom.xml, the &gt and &lt and some / used in <br /> are not being parsed out, and are appearing in the html. Any ideas?

If you send me the feed URL I can check it out

Esteban 20 July, 2009

First of all, your RSS Feed Reader class is great. Thanks for sharing it.

I've been using without major problems; although, I find one little issue I could not resolve yet: I would like to change the date format that comes within the item->pubdate tag to something more friendly. Could you guys give any ideas?

A few people have asked about this. I suggest something like the following:

if($PUBDATE) {
  $PUBDATE = date('l, jS F Y', strtotime($PUBDATE));
  $tmp[] = "<small>Published: $PUBDATE</small>";
}

Jeff Quiros 21 September, 2009

Your class.myrssparser.php has been extremely helpful to me in understanding creating/displaying RSS feeds, but in the code as copied onto my server. I get a huge string of error messages. The first few are as follows:
Notice: Undefined index: CHANNEL in C:InetpubVTRADERRfactorcla­ss.myrssparser.php on line 42

Notice: Undefined variable: RSS in ...
Notice: Undefined index: RSS in ...
Notice: Undefined index: LINK in ...

The errors you're seeing are really "Notices" saying that a variable (array index) is being referenced without previously being created/initialised. You can suppress these messages by setting your error_reporting level in PHP to "E_ALL ^ E_NOTICE" so it displays only actual errors and warnings and not notices.

anthony 9 January, 2011

I got an error.
Error: unrecognized start tag 'FEED' in getOutput()

can you please explain

See comments above.

ryan 12 April, 2011

this solution is fantastic. one question though: if i was to include a truncate function to truncate each entry to a certain number of words, where would i put that in the code? i was reading your other page on truncating and couldn't figure out how to merge the two.

thanks a bunch.

You can truncate the DESCRIPTION field in the display_item function just before it's added to the return string:
e.g.
$DESCRIPTION = myTruncate($DESCRIPTION, 200);
$this->retval .= "<p>" . stripslashes($DESCRIPTION) . "</p>\n\n";


Alex 21 June, 2011

Tks for your greate post, beside I have one question that is :
How can I use this code to put rss from two source on one page ?

You only need to include the PHP class one time. The code that follows can then be repeated as many times as you want on the page, though it's probably a good idea use caching.

shadmego 4 September, 2011

Is there a way to alter the class so it doesn't fail when encountering "undefined entities"?

The feed I am displaying apparently has some characters that the script doesn't understand and it is causing my page to fail with the error: "myRSSParser: Error undefined entity at line 385"

Line 385 would be the line in the cache file being read by the script.

The RSS feed reader class relies on the XML Parser extension included with PHP. That is where the error is being thrown rather then from our code (ref: php.net/xml_parse).

To avoid XML errors you need to make sure that the input is valid, or maybe just tweak the character-encoding or use utf8_encode if that's the problem..

For your particular case you can insert the following patch:


while($data = fread($fp, 4096)) {
if(!in_array(mb_detect_encoding($data), array("UTF-8", "ASCII"))) {
$data = preg_replace('[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S', '?', $data);
}
xml_parse(...) or die(


Jonathan Wheat 22 September, 2011

Love the parser.
I had something like this in my feed

6:00 PM

and added

$tagname = ereg_replace(":","",$tagname);

inside startElement, then could reference the variable as MCSTARTTIME

I would use str_replace instead of the ereg function which is now deprecated, but yes, that's a good way to extract other variables

Alexej Savčin 9 October, 2011

Hi there. I shuld say this parser was perfect solution to my problem but I have one issue. I can't set number of showing feeds. Can you help me with this?

What you're looking for is just:

$output = $rss_parser->getOutput(3);

This will limit the display to the first 3 items in the feed.

Send Feedback

Send Your Feedback (will not be published) (optional) CAPTCHA refresh <- copy the digits from the image into this box

[top]