-1

我只想在我的网站上显示最新的 5 个提要。
我正在使用以下代码来获取 rss 提要...任何人都可以帮助显示有限的提要...谢谢您提前:)

正在使用的代码

<?php
 require_once('rss_fetch.inc');

 $url = 'http://news.google.com/news?ned=us&topic=h&output=rss';

 $rss = fetch_rss($url);

 echo "Site: ", $rss->channel['title'], "<br>\n";
 foreach ($rss->items as $item ) {
   $title = $item['title'];
   $url   = $item['link'];
   $desc = $item['description'];
   $category = $item['category'];
   echo "<a href=$url>$title</a>$desc <br/>CATEGORY : $category <br/><br/> ";
 }
?>
4

2 回答 2

2

限制它使用foreach?

 foreach ($rss->items as $i => $item ) { // use $i as counter
   $title = $item['title'];
   $url   = $item['link'];
   $desc = $item['description'];
   $category = $item['category'];
   echo "<a href=$url>$title</a>$desc <br/>CATEGORY : $category <br/><br/> ";
   if($i == 4) break; // add this, == 4 is because $i starts from 0
 }
于 2012-05-25T08:47:57.603 回答
1

如果您希望限制帖子的数量,您只需要跟踪它们并在适用时打破 foreach 循环,例如

<?php
 require_once('rss_fetch.inc');

 $url = 'http://news.google.com/news?ned=us&topic=h&output=rss';

 $rss = fetch_rss($url);

 echo "Site: ", $rss->channel['title'], "<br>\n";
 $numposts = 0;
 $maxposts = 5;
 foreach ($rss->items as $item ) {
   $numposts++;
   if ($numposts<=$maxposts) {
     $title = $item['title'];
     $url   = $item['link'];
     $desc = $item['description'];
     $category = $item['category'];
     echo "<a href=$url>$title</a>$desc <br/>CATEGORY : $category <br/><br/> ";
   } else {
     break;
   }
 }
?>
于 2012-05-25T08:47:56.247 回答