Skip to content
ujang-jelebu edited this page Sep 19, 2012 · 31 revisions

Category:Library::Community | Category:Library::RSS

Introduction

I have created this page to document the RSSParser library I have put together. I wanted to add RSS items and couldn't find anything to achieve this and so have put this together for anyone else that would like it.

The RSS parsing was adapted closely from here

Because the class is loading an externally hosted file performance van very wildly so I have added some simple caching into the class.

The class is only on its first revision so there may well be bugs within it, if you find any please let me know and I will be happy to look into them.

If anyone has any suggestions or comments I'd be happy to hear them

Cheers

/Matt

Instructions

In order to make use of this library simply copy and paste this class into a php file called RSSParser.php and save it into your libraries file (system/application/libraries/). You can then load this library as you would any other library within your application.

Example

The below code demonstrates how you would use the RSSParser class

  //Load the shiny new rssparse
  $this->load->library('RSSParser', array('url' => 'http://link.to/rss.xml', 'life' => 2));
  //Get six items from the feed
  $data = $this->rssparser->getFeed(6);

  foreach ($data as $item) :
    // do stuff with $item['title'], $item['description'], etc.
  endforeach;

The constructor expects the url of the rss feed, and the lifetime of the cache file in minutes. The getFeed function expects the number of feed items you would like to retrieve.

Source

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/*
 * This class is written based entirely on the work found below
 * www.techbytes.co.in/blogs/2006/01/15/consuming-rss-with-php-the-simple-way/
 * All credit should be given to the original author
*/

class RSSParser
{
    // ===================//
    //Instance vars       //
    // ===================//

    /* Feed URI */
    var $feed_uri;

    /* Associative array containing all the feed items */
    var $data;

    /* Store RSS Channel Data in an array */
    var $channel_data;

    /*  Boolean variable which indicates whether an RSS feed was unavailable */
    var $feed_unavailable;

    /* Cache lifetime */
    var $cache_life;

    /* Flag to write to cache - defaulted to false*/
    var $write_cache_flag = false;

    /* Code Ignitor cache directory */
    var $cache_dir;

    // ================ //
    // Constructor      //
    // ================ //
    function RSSParser($params) {
          $this->CI =& get_instance();
          $this->cache_dir = ($this->CI->config->item('cache_path') == '') ? FCPATH.APPPATH.'cache/' : $this->CI->config->item('cache_path');

          //$this->cache_dir = '/system/cache';
          $this->cache_life = $params['life'];
    
          $this->feed_uri = $params['url'];
          $this->current_feed["title"] = '';
          $this->current_feed["description"] = '';
          $this->current_feed["link"] = '';
          $this->data = array();
          $this->channel_data = array();
    
          //Attempt to parse the feed
          $this->parse();
    }

    // =============== //
    // Methods         //
    // =============== //
    function parse() {
        //Are we caching?
        if ($this->cache_life != 0)
        {

            $filename = $this->cache_dir.'rss_Parse_'.md5($this->feed_uri);

            //is there a cache file ?
            if (file_exists($filename))
            {
                //Has it expired?
                $timedif = (time() - filemtime($filename));
                if ($timedif < ( $this->cache_life * 60))
                {
                    //its ok - so we can skip all the parsing and just return the cached array here
                    $this->data = unserialize(implode('', file($filename)));
                    return true;
                }
               //So raise the falg
               $this->write_cache_flag = true;

            } else {
               //Raise the flag to write the cache
               $this->write_cache_flag = true;
            }
       }


      //Parse the document
      $rawFeed = file_get_contents($this->feed_uri);
      $xml = new SimpleXmlElement($rawFeed);

      //Assign the channel data
      $this->channel_data['title'] = $xml->channel->title;
      $this->channel_data['description'] = $xml->channel->description;

      //Build the item array
      foreach ($xml->channel->item as $item)
      {
           $data = array();
           $data['title'] = (string)$item->title;
           $data['description'] = (string)$item->description;
           $data['pubDate'] = (string)$item->pubDate;
           $data['link'] = (string)$item->link;
           $this->data[] = $data;
      }

      //Do we need to write the cache file?
      if ($this->write_cache_flag)
      {
            if ( ! $fp = @fopen($filename, 'wb'))
            {
                echo "ERROR";
                log_message('error', "Unable to write cache file: ".$cache_path);
                return;
            }
            flock($fp, LOCK_EX);
            fwrite($fp, serialize($this->data));
            flock($fp, LOCK_UN);
            fclose($fp);
      }
      return true;
  }

    /* Return the feeds one at a time: when there are no more feeds return false
     * @param No of items to return from the feed
     * @return Associative array of items
    */
    function getFeed($num) {
        $c = 0;
        $return = array();
        foreach($this->data AS $item)
        {
            $return[] = $item;
            $c++;
            if($c == $num) break;
        }
        return $return;
    }

    /* Return channel data for the feed */
    function & getChannelData() {
        $flag = false;
         if(!empty($this->channel_data)) {
            return $this->channel_data;
        } else {
            return $flag;
        }
    }

    /* Were we unable to retreive the feeds ?  */
    function errorInResponse() {
       return $this->feed_unavailable;
    }

}

?>;
Clone this wiki locally