我正在浏览BBC新闻XML Feed.但我想要做的是限制它说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 } ?>
Run Code Online (Sandbox Code Playgroud)
提前致谢..
使用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
);
}
Run Code Online (Sandbox Code Playgroud)
通过DOM对象交换对象,你会变得更轻一些SimpleXML- 而且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) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
取一个计数器变量,每次迭代递增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
} ?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6435 次 |
| 最近记录: |