Limiting results with PHP SimpleXML

While parsing an RSS feed with SimpleXML, is certainly useful to limit the number of items fetched with the simplexml_load_file() method. Suppose that we want to parse a Twitter feed and we want only the first five items. We could write the following:

  $rss = simplexml_load_file('');
  $items = $rss->channel->item;
  $i = -1;
  do {
       $raw_title = $items[$i]->title;
        $title = str_replace('gabromanato:', '', $raw_title);
        $title = preg_replace('/http.+/', '', $title);
        $raw_date = $items[$i]->pubDate;
        $date = str_replace('+0000', '', $raw_date);
        $link = $items[$i]->link;
         echo '<li><a href="' . $link . '">' . $title . '</a>' . "\n" . '<div class="pubdate">' . $date . '</div>' . "\n" . "</li>\n";                               
  } while($i < 5);

We're actually using a do.. while loop here. Every time we increment our internal counter, we move to the next item in the array. Since the returned array starts from 0, we set our counter to -1 to start from the very first item. You can see a test here.

Leave a Reply

Note: Only a member of this blog may post a comment.