2013-04-21 109 views
1

下面大致顯示了我用來顯示源中項目的內容。它工作正常,但Feed中有很多項目,我希望能夠顯示Feed中的前5個項目。這個如何完成?限制顯示的Feed項目數

<?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 .''; 

    } ?> 

回答

1
foreach ($result as $i => $item) { 
    if ($i == 5) { 
     break; 
    } 
    echo 'The title is '.$item->title.' and the date is '. $item->date; 
} 
+0

完美,謝謝 – user2227359 2013-04-21 21:14:40

-1

for迴路可以比foreach環路更適合這個:

for ($i=0; $i<=4; $i++) { 
    echo 'The title is '.$result[$i]->title.' and the date is '. $result[$i]->date; 
} 

該環具有在不修改所述陣列中的任何東西,高得多的性能,所以如果速度事項我會推薦它。

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 . ''; 
} 
?>

Here's a demo!