How to Easily Parse a RSS Feed with PHP 4 or PHP 5

Today I had to parse a WordPress RSS feed for display on a customers website. The basic goal was to show the latest blog postings on the customer’s homepage without them having to manually feed in the data. I have done this before using some of the great XML tools in PHP 5 that make this kind of task a breeze. Unfortunately, the customer’s website resides on another company’s server and they only have PHP 4 available. It had been a long time since I had parsed an RSS feed for PHP 4 but I dug up this handy function I used to use frequently back in the PHP 4 days. It works in PHP 4 or PHP 5 and makes parsing an RSS feed a piece of cake. Basically it parses the feed and returns an array of the results.

Below is the sample code that shows how this is done. The first section has the parseRSS() function and the second part is an example of me calling the function on my blog RSS feed. If you copy the code straight away you should see in your browser the last 10 entries from your favorite blog… mine.

<?PHP
 
	/******************************************************************************************************************
	   RSS PARSING FUNCTION
	******************************************************************************************************************/
 
	//FUNCTION TO PARSE RSS IN PHP 4 OR PHP 4
	function parseRSS($url) { 
 
	//PARSE RSS FEED
        $feedeed = implode('', file($url));
        $parser = xml_parser_create();
        xml_parse_into_struct($parser, $feedeed, $valueals, $index);
        xml_parser_free($parser);
 
	//CONSTRUCT ARRAY
        foreach($valueals as $keyey => $valueal){
            if($valueal['type'] != 'cdata') {
                $item[$keyey] = $valueal;
			}
        }
 
        $i = 0;
 
        foreach($item as $key => $value){
 
            if($value['type'] == 'open') {
 
                $i++;
                $itemame[$i] = $value['tag'];
 
            } elseif($value['type'] == 'close') {
 
                $feed = $values[$i];
                $item = $itemame[$i];
                $i--;
 
                if(count($values[$i])>1){
                    $values[$i][$item][] = $feed;
                } else {
                    $values[$i][$item] = $feed;
                }
 
            } else {
                $values[$i][$value['tag']] = $value['value'];  
            }
        }
 
	//RETURN ARRAY VALUES
        return $values[0];
	} 
 
 
	/******************************************************************************************************************
	  SAMPLE USAGE OF FUNCTION
	******************************************************************************************************************/
 
	//PARSE THE RSS FEED INTO ARRAY
	$xml = parseRSS("http://www.stemkoski.com/?feed=rss2");
 
	//SAMPLE USAGE OF 
	foreach($xml['RSS']['CHANNEL']['ITEM'] as $item) {
	        echo("<p class=\"indexBoxNews\"><a href=\"{$item['LINK']}\" target=\"_blank\" class=\"indexBoxNews\">{$item['TITLE']}{$link}</a></p>");
	}
 
?>

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

effing perfect!

Hi there,
Thanks! I ‘ve been looking for a way to do this. I used to know a little php and my server uses old php4.

I get a strange character before my list : 

Is there a way I can easily limit the number of entries shown? To limit it to the most recent 3 entries?

Thanks,
Steve in Canada

[...] PHP4 as well because the client is on one of our older servers. I ended up finding a really good example by Ryan Stemkoski. He wrote a perfect function for me to tweak a little and expand upon. I am currently waiting to [...]

Hey Ryan:

I wanted to thank you for posting this code. It saved quite a bit of time trying to get started. I wanted to let you know I have modified your code a little bit to allow you to limit the number of items as well as only contain items that where the title matches certain keywords. I also turned my modifications into a WordPress plugin as well.

If you, or anyone else, would like to see my modifications or WordPress plugin please check out http://techno-geeks.org/2009/06/selective-rss-plugin-for-wordpress/

Hey,

many thanks from Darmstadt / Germany. That was exactly what I was looking for! I changed the script and now it is a php to flash twitter reader.

CIAO Dennis

Hi There,
Many thanks for this function. A customer needed me to update a page that had broken when the site serving an RSS page changed its format. It had been years since I parsed RSS using PHP4, and I was not looking forward to it. Lucky for me, about 20 minutes with your script and a small addition, and I was on my way.

Much appreciated!
Matt

@Matt Glad to hear it worked out for you. Turning an RSS feed into an array makes it pretty handy to display the data. What is even easier is using the built in functions in PHP 5 :) too bad the world isn’t totally on board yet.

Nice work. Thanks for sharing.

This has saved me a ton of time on a project that needed to be done quickly. So Painless … Thx!

@zaner, @arun m I am glad to hear it worked well for you guys.

This is great, thanks for posting! Only thing I wish it could do is store the CATEGORY tag as an array because often a post has more than category assigned. The above code only saves the first CATEGORY tag. I’d change it, but, not sure how to do it myself. If anyone knows how to change the code to make it save CATEGORies as an array, I’d greatly appreciate it!!

This works great! I wish I had found this four hours earlier so I didn’t have to waste all that time searching!

For those who want do display by category, by default, if you set a category there’s an html path that wordpress generates.
You can get the rss feed url to such category trough the respective “category folder path/feed”.

PE:
http://yourblog.wordpress.com/category/yourcategoryname/feed/

Replacing “yourblog” and “yourcategoryname” by their respectives.

Dunno if other blogs do so.
I use the PHP GET function to select wich blog or category I want to call.

Nice work. It doesn’t work on all RSS feeds though. I get a PHP Fatal error: [] operator not supported for strings in /var/www/html/phpparser.php on line 39
with this feed: http://www.mxi.nl/nieuws/rssfeed.xml.

Now this feed isn’t generated by wordpress, but it is pretty clean coded. Any ideas on how to fix it?

thanks

@Williem Sorry it has taken me so long to get around to your comment. I tried to parse your RSS feed myself using the script but it didn’t work for me either. Not quite sure what it is about your feed but I couldn’t make it work with a little debugging. You might try using PHP SimpleXML to see if it reads it: http://blog.stuartherbert.com/php/2007/01/07/using-simplexml-to-parse-rss-feeds/

Hello

Nice script, thank you.

But there is images in my feed, how can i get them?

Hi,
unfortunately i get this error since today:

Fatal error: [] operator not supported for strings in … on line 85

line 85 is the line $values[$i][$item][] = $feed; out of the following part of your script:

foreach($item as $key => $value){

if($value['type'] == ‘open’) {

$i++;
$itemame[$i] = $value['tag'];

} elseif($value['type'] == ‘close’) {

$feed = $values[$i];
$item = $itemame[$i];
$i–;

if(count($values[$i])>1){
$values[$i][$item][] = $feed;
} else {
$values[$i][$item] = $feed;
}

} else {
$values[$i][$value['tag']] = $value['value'];
}
}

//RETURN ARRAY VALUES
return $values[0];
}

Help please! I can mail you my script…

Here is a simple script that i use for my website http://bncscripts.com/item-21/bnc-advanced-feed-parser-2-0/
Hope that helps someone

Works nicely, thanks.

thanks very much for your script; it works fine for me (reading wordpress rss). There is just this: when I check the rss I noticed that there are no complete posts in there; only a description containing a part of the text. Do you know where I can get the full text of my blogposts?
thnx in advance!

@Ruben You may need to enabled full text RSS output in your WordPress settings.

Leave a comment

(required)

(required)