You are here:  » limiting # of items when parsing rss feed?


limiting # of items when parsing rss feed?

Submitted by dflsports on Fri, 2006-08-04 03:10 in

I just starting experimenting parsing RSS feeds using magic parser.

Just using the example provided in the manual

<?php
  
require("MagicParser.php");
  function 
myRecordHandler($item)
  {
    print 
"<h4><a href='".$item["LINK"]."'>".$item["TITLE"]."</a></h4>";
    print 
"<p>".$item["DESCRIPTION"]."</p>";
  }
  print 
"<h3>News from Blog XYZ</h3>";
  
$url "http://domain.com/blog.rss";    
  
MagicParser_parse($url,"myRecordHandler","xml|RSS/CHANNEL/ITEM/");
?>

How can I limit the number of items shown? I'd like to show the last 5 posts instead of all that are in the RSS feed.

Thanks!

Submitted by support on Fri, 2006-08-04 05:01

Hi,

It is easy to limit the parsing to the first n records because the Parser will stop reading any more records if your record handler function returns true,

Therefore, all you need to do is setup a global counter, increment the counter for each record and make myRecordHandler return TRUE when you have read as many records as you want. For example:

<?php
  
require("MagicParser.php");
  
$counter 0;
  function 
myRecordHandler($item)
  {
    global 
$counter;
    
// increment counter
    
$counter++;
    print 
"<h4><a href='".$item["LINK"]."'>".$item["TITLE"]."</a></h4>";
    print 
"<p>".$item["DESCRIPTION"]."</p>";
    
// return true when counter reaches 5
    
return ($counter == 5);
  }
  print 
"<h3>News from Blog XYZ</h3>";
  
$url "http://domain.com/blog.rss";
  
MagicParser_parse($url,"myRecordHandler","xml|RSS/CHANNEL/ITEM/");
?>

It may be that the newest items are first in the RSS feed that you are using, so this is all you need to do.

However, if you want the last 5 items in the feed then it is more complicated because you have no choice but to read all the records (as the parser does not know how many records there are until they are read). In this scenario, you will need to read all records into an array, and then display whichever records you require from that array. One way to do it is like this:

<?php
  
require("MagicParser.php");
  
$items = array();
  function 
myRecordHandler($item)
  {
    global 
$items;
    
// add current item to global items array
    
$items[] = $item;
  }
  print 
"<h3>News from Blog XYZ</h3>";
  
$url "http://domain.com/blog.rss";
  
MagicParser_parse($url,"myRecordHandler","xml|RSS/CHANNEL/ITEM/");
  
// having read all items, display the last 5:
  
for($i=1;$i<=5;$i++)
  {
     
$item array_pop($items);
     print 
"<h4><a href='".$item["LINK"]."'>".$item["TITLE"]."</a></h4>";
     print 
"<p>".$item["DESCRIPTION"]."</p>";
  }
?>

Hope this helps!
David.

Submitted by dflsports on Fri, 2006-08-04 13:17

Thanks David!