我正在浏览BBC新闻XML提要。但是我想做的是将它限制为8或10个提要条目。
我怎样才能做到这一点?
我的代码是:<?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 } ?>
Thanks in advance.
使用XPath可以很容易地检索RSS提要的子集。
$itemCount = 10;
$xml = simplexml_load_file('http://feeds.bbci.co.uk/news/rss.xml');
$items = $xml->xpath(sprintf('/rss/channel/item[position() <= %d]', $itemCount));
foreach ($items as $i) {
$itemRSS = array (
'title' => (string)$i->title,
'desc' => (string)$i->description,
'link' => (string)$i->link,
'date' => (string)$i->pubDate
);
}
通过用SimpleXML
对象交换DOM
对象,您的重量会轻一些—并且XPath更容易与SimpleXML
一起使用(这就是我在本例中使用它的原因)。对DOM
也可以这样做:
$doc = new DOMDocument();
$doc->load('http://feeds.bbci.co.uk/news/rss.xml');
$xpath = new DOMXpath($doc);
$items = $xpath->query(sprintf('/rss/channel/item[position() <= %d]', $itemCount));
foreach ($items as $i) {
// ...
}
取一个计数器变量,每次迭代递增1,检查计数器是否达到上限,然后退出循环。
$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
} ?>
当您使用SimpleXml
时,您也可以使用array_slice
:
$rss = simplexml_load_file('http://feeds.bbci.co.uk/news/rss.xml');
$items = $rss->xpath('/rss/channel/item');
$startAtItem = 0;
$numberOfItems = 9;
$firstTenItems = array_slice($items, $startAtItem, $numberOfItems);
或带LimitIterator
:
$rss = simplexml_load_file('http://feeds.bbci.co.uk/news/rss.xml');
$items = $rss->xpath('/rss/channel/item');
$startAtItem = 0;
$numberOfItems = 9;
$firstTenItems = new LimitIterator(
new ArrayIterator($items), $startAtItem, $numberOfItems
);
foreach ($firstTenItems as $item) { …
更优雅的是本站点其他地方提供的XPath position()
解决方案。