Categories
PHP

Read RSS in PHP with cache

Simple function to read RSS where you can set some values:

function rssReader($url,$maxItems=15,$begin="",$end=""){
        $rss = simplexml_load_file($url);
        $i=0;
        if($rss){
            $items = $rss->channel->item;
            foreach($items as $item){
                if($i==$maxItems) return $out;
                else $out.=$begin.''.$item->title.''.$end;
                $i++;
            }
        }
        return $out;
    }

Usage example:

echo '
    '.rssReader('https://garridodiaz.com/feed/',5,'
  • ','
  • ').'
';

Using cache with the class fileCache:

 function rssReader($url,$maxItems=15,$cache,$begin="",$end=""){
        $cache= (bool) $cache;
        if ($cache){
            $cacheRSS= new fileCache();//seconds and path
            $out = $cacheRSS->cache($url);//getting values from cache
        }else $out=false;

        if (!$out) {	//no values in cache
            $rss = simplexml_load_file($url);
            $i=0;
            if($rss){
                $items = $rss->channel->item;
                foreach($items as $item){
                    if($i==$maxItems){
                        if ($cache) $cacheRSS->cache($url,$out);//save cache
                        return $out;
                    }
                    else $out.=$begin.''.$item->title.''.$end;
                    $i++;
                }
            }
        }
        return $out;
    }

Usage example RSS with cache:

echo '
    '.rssReader('https://garridodiaz.com/feed/',5,true,'
  • ','
  • ').'
';

Based on this one from sihan:

 $url = "http://news.google.com/?ned=us&topic=t&output=rss";
    $rss = simplexml_load_file($url);
    if($rss){
        echo '

'.$rss->channel->title.'

'; echo '
  • '.$rss->channel->pubDate.'
  • '; $items = $rss->channel->item; foreach($items as $item){ $title = $item->title; $link = $item->link; $published_on = $item->pubDate; $description = $item->description; echo '

    '.$title.'

    '; echo '('.$published_on.')'; echo '

    '.$description.'

    '; } }