如何只显示5条记录? [英] how to display only 5 records?

查看:108
本文介绍了如何只显示5条记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是读取rssfeed,所以我已经做到了,但是我显示为foreach循环,所以我怎么只显示5条记录?现在我获得了10条以上的记录,但是我只需要前5条记录,无论是php,javascript还是jquery都不会只显示5条记录?

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?

这是我读取rss文件的代码:

here is my code to read the rss file:

function getrssFeed($feed_url) {

$content = file_get_contents($feed_url);    
$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");

谢谢

推荐答案

最简单的方法是在5次迭代后停止循环:

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;
  }  
}

另一种(更漂亮的)方法是使用for -loop而不是foreach:

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
}


感谢Juhana,我更改了代码以考虑到这一点.

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

这篇关于如何只显示5条记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆