以下是我用来显示Feed中的项目的大致内容。它工作正常,但Feed有很多项目,我希望能够只显示Feed中的前5项。这怎么办?
<?php
$theurl = 'http://www.theurl.com/feed.xml';
$xml = simplexml_load_file($theurl);
$result = $xml->xpath("/items/item");
foreach ($result as $item) {
$date = $item->date;
$title = $item->title;
echo 'The title is '. $title.' and the date is '. $date .'';
} ?>
答案 0 :(得分:1)
foreach ($result as $i => $item) {
if ($i == 5) {
break;
}
echo 'The title is '.$item->title.' and the date is '. $item->date;
}
答案 1 :(得分:0)
for
循环可能比foreach
循环更适合:
for ($i=0; $i<=4; $i++) {
echo 'The title is '.$result[$i]->title.' and the date is '. $result[$i]->date;
}
当不修改数组中的任何内容时,此循环具有更高的性能,因此如果速度很重要,我建议它。
答案 2 :(得分:0)
只需将其作为XPath查询的一部分:
<?php
$theurl = 'http://www.theurl.com/feed.xml';
$xml = simplexml_load_file($theurl);
$result = $xml->xpath('/items/item[position() <= 5]');
foreach ($result as $item) {
$date = $item->date;
$title = $item->title;
echo 'The title is '. $title.' and the date is '. $date . '';
}
?>