2011-08-25 34 views
0

如何添加一個偏移量和限制到我的PHP rss解析器返回結果作爲一個對象?,這裏是我目前的。它沒有任何抵消和限制,如何解決這個問題?如何添加偏移量和限制到我的php rss解析器?

class Rss 
{ 
    /* 
    *@access public 
    *@params url,int ''=default,int ''=default 
    *@usage input url,offset and limit, 
    *@returns content based onf the offset/limit input 
    */ 
    public function getFeed($url,$offset='',$limit=''){ 
     $object = array(); 
     $rss = simplexml_load_file($url); 
     foreach($rss->channel->item as $item){ 
      $object[] = $item->title; 
      $object[] = $item->description; 
      $object[] = $item->link; 
     } 
    return $object; 
    } 
} 

回答

1

當然Simpliest方式

$limit = 10; $offset = 5; 
$i=0; $taken=0; 
foreach($rss->channel->item as $item){ 
    if ($i>=$offset && $taken<$limit){ 
     ++$taken; 
     $object[] = $item->title; 
     $object[] = $item->description; 
     $object[] = $item->link; 
    } 
    //little optimization here 
    if ($taken == $limit) 
     break; 
    ++$i; 
} 

你可以存儲$limit$offset爲對象的屬性,或讓他們在其他地方。

1

單身櫃檯的事情呢?根據需要

public function getFeed($url,$offset='',$limit=''){ 
    $object = array(); 
    $rss = simplexml_load_file($url); 
    $offset = 3; $limit = 8; $counter = 0; 
    foreach($rss->channel->item as $item){ 
     $counter++; 
     if ($counter > $offset && $counter < $limit) { 
     $object[] = $item->title; 
     $object[] = $item->description; 
     $object[] = $item->link; 
     } 
    } 
return $object; 

}

1

集偏移/限制可以使用SimpleXMLElement::xpath。這樣你就不必遍歷所有項目來計算事物。

public function getFeed($url, $offset = 1, $limit = -1){ 
    $object = array(); 
    $rss = simplexml_load_file($url); 

    $limitCriteria = ''; 
    if ($limit > 0) { 
     $limitCriteria = 'and position() <= ' . ((int)$offset + (int)$limit + 1); 
    } 

    foreach($rss->xpath(sprintf('//item[position() >= %s %s]', (int)$offset, $limitCriteria)) as $item){ 
     $object[] = $item->title; 
     $object[] = $item->description; 
     $object[] = $item->link; 
    } 

    return $object; 
    }