Php 限制显示的提要项目数

Php 限制显示的提要项目数,php,simplexml,Php,Simplexml,下面是我用来显示提要中项目的大致内容。它工作得很好,但是提要有很多项,我希望能够只显示提要中的前5项。这是怎么做到的 <?php $theurl = 'http://www.theurl.com/feed.xml'; $xml = simplexml_load_file($theurl); $result = $xml->xpath("/items/item"); foreach ($result as $item) { $dat

下面是我用来显示提要中项目的大致内容。它工作得很好,但是提要有很多项,我希望能够只显示提要中的前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 .'';

    } ?>
xpath(“/items/item”);
foreach($result作为$item){
$date=$item->date;
$title=$item->title;
echo“标题为“.$title.”,日期为“.$date.”;
} ?>

for的
循环可能比foreach的
循环更适用于此:

for ($i=0; $i<=4; $i++) {
    echo 'The title is '.$result[$i]->title.' and the date is '. $result[$i]->date;
}
for($i=0;$ititle.”,日期为“$result[$i]->date;
}

当不修改数组中的任何内容时,此循环具有更高的性能,因此如果速度很重要,我建议使用它。

只需将其作为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 . '';
}
?>
xpath('/items/item[position()
<?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 . '';
}
?>