how to add offset and limit to my php rss parser?
how to add an offset and limit to my PHP rss parser that returns the result as an object ?, here is what i have at the moment. it doesn't have any offset nor limit, how to approach this ?
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;
}
}
Simpliest way
$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;
}
Of course you can store $limit
and $offset
as object properties, or get them elsewhere.
how about a single counter thing? set offset/limit as needed
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;
}
You can use SimpleXMLElement::xpath. This way you don't have to traverse all items just for counting things.
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;
}
精彩评论