开发者

how to display only 5 records?

What i want to do is read rssfeed, so I already did it, but I display as foreach loop, so how can I only display 5 records ? now I get more than 10 records, but I only need top 5 records, Isn't anyway php, javascript or jquery make it only show 5 records?

here is my code to read the rss file:

function getrssFeed($feed_url) {

$content = file_get_contents($feed_url);    
开发者_Python百科$x = new SimpleXmlElement($content);
echo "<ul>";

foreach($x->channel->item as $entry) {      
     echo "<li><a href = '$entry->link' title='$entry->title'><h3>" . $entry->title . "</h3></a>" . $entry->pubDate . "<br /><br />" . strip_tags($entry->description) . "</li>";   
}
echo "</ul>";   }

getrssFeed("http://thestar.com.my.feedsportal.com/c/33048/f/534555/index.rss");

thank you


the easiest way would be to stop your loop after 5 iterations:

$i = 0;
foreach($x->channel->item as $entry) {      
  // do something
  $i++;
  if($i==5){
    break;
  }  
}

another (more beautiful) way would be to use a for-loop instead of foreach:

for($i=0; $i<=min(5, count($x->channel->item)); $i++) {   
  $entry = $x->channel->item[$i];
  // do something
}

EDIT :
thanks to Juhana, i changed the code to take that into account.


Try putting a counter in your foreach loop with an if statement to check when the counter is over 5. If the counter is under 5 -> display RSS post, counter++. Else -> Exit loop.


Why not use a simple for loop instead?

for($i = 0, $i <= 5, $i++) {      
    echo "<li><a href = '$x->channel->item[$i]->link' title='$x->channel->item[$i]->title'><h3>" . $x->channel->item[$i]->title . "     </h3></a>" . $x->channel->item[$i]->pubDate . "<br /><br />" . strip_tags$x->channel->item[$i]->description) . "</li>";   
}


You can use jQuery feed Plugin.

    $('div.feed').Feed({
    count:5;
    });
    <div class="feed" link="http://thestar.com.my.feedsportal.com/c/33048/f/534555/index.rss" ></div>

Feeds would be loaded to container feed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜