-2

My code below is getting the entire RSS feed, how can I limit this to just retrieve the latest 3 posts? Either that or simply display just the latest 3 and not all posts.

<?php
$xml=simplexml_load_file("http://tutorial.world.edu/feed/");
foreach ($xml->channel->item as $item) {
    $title = (string) $item->title; // Title Post
    $link   = (string) $item->link; // Url Link
    $pubDate   = (string) $item->pubDate; // date
    $description = (string) $item->description; //Description Post
echo '<div class="display-rss-feed"><a href="'.$link.'" target="_blank" title="" >'.$title.' </a><br/><br/>';
echo $description.'<hr><p style="background-color:#e4f;">'.$pubDate.'</p></div>';
 }
?>
egr103
  • 3,858
  • 15
  • 68
  • 119

2 Answers2

1

A simple way to do that is to count. Starting with zero and counting per each iteration, you just exit the loop if the counter reaches four.

Another possibility is to use the LimitIterator on an IteratorIterator on the Traversable you've got in question ($xml->channel->item).

This is outlined here:

And further related to your question are:

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
0

you can use array_slice($xml->channel->item, 0, 3) in for sothat it grap only up to 3 first posts

ovgu12
  • 130
  • 2
  • 8