如何只显示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.