XML Feeds &PHP - 限制项目数量 [英] XML Feeds & PHP - Limit the number of items

查看:32
本文介绍了XML Feeds &PHP - 限制项目数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览 BBC 新闻 XML 提要.但我想要做的是将其限制为提要的 8 或 10 项.

I am pulling through the BBC News XML Feed. But what I want to do is limit it to say 8 or 10 items of the feed.

我怎样才能做到这一点?

How can I achieve this?

我的代码是:

<?php

  $doc = new DOMDocument();
  $doc->load('http://feeds.bbci.co.uk/news/rss.xml');
  $arrFeeds = array();
  foreach ($doc->getElementsByTagName('item') as $node) {
    $itemRSS = array ( 
      'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
      'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
      'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
      'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
      );
?>

<h2><a href="<?php echo $itemRSS['link'] ;?>"><?php echo $itemRSS['title']; ?></a></h2>
<?php  } ?>

提前致谢..

推荐答案

取一个计数器变量,每次迭代加一,检查计数器是否达到上限,然后退出循环.

Take a counter variable, increment by one with each iteration and check if the counter is reached at the upper limit and then exit from loop.

$cnt=0;
foreach ($doc->getElementsByTagName('item') as $node) {
    if($cnt == 8 ) {
       break;
     }    
    $itemRSS = array ( 
      'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
      'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
      'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
      'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
      );
      $cnt++;
?>    
<h2><a href="<?php echo $itemRSS['link'] ;?>"><?php echo $itemRSS['title']; ?></a></h2>
<?php 
} ?>

这篇关于XML Feeds &amp;PHP - 限制项目数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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