RSS Feed reader – simple PHP class

A while ago I wrote my own RSS reader. It wasn’t that hard. But, occasionally you stumple across code like this example below that does the same thing as yours does, but sort of puts yours to shame. (Well, my version is about 3 years old now…).

So I cut down the original class and kept the bits I needed – and transferred all my implementations to the new method. Nothing changed on the front end, but I learnt a lot…

getFeed($url);
  //foreach($feed as $item)    {
  //    echo "Title: $item[title]\n";
  //    echo "Published: $item[date]\n";
  //    echo "\n$item[description]\n";
  //    echo "
"; //} */ /** * Rss Feed Reader * This is a cut-down a d minifies version of "Daniel Tlach's" excellent class * ORIGINAL CLASS :: Copyright 2007-2009, Daniel Tlach * :: Licensed under GNU GPL * @copyright Copyright 2007-2009, Daniel Tlach * @link http://www.danaketh.com * @version 2.1 * @license http://www.gnu.org/licenses/gpl.txt */ class Rss { private $parser; private $feed_url; private $item; private $tag; private $output; private $counter = 0; private $title = NULL; private $description = NULL; private $link = NULL; private $pubDate = NULL; function __construct( ) { } public function getFeed($url) { $this->counter = 0; return $this->xmlParser($url); } private function xmlParser($url) { $this->parser = xml_parser_create(); xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); $this->feed_url = $url; xml_set_object($this->parser,&$this); xml_set_element_handler($this->parser, "xmlStartElement", "xmlEndElement"); xml_set_character_data_handler($this->parser, "xmlCharacterData"); $this->xmlOpenFeed(); return $this->output; } private function xmlOpenFeed() { $feed = file_get_contents($this->feed_url); xml_parse($this->parser, $feed, TRUE); xml_parser_free($this->parser); } private function xmlStartElement($parser, $tag) { if ($this->item === TRUE) { $this->tag = $tag; } else if ($tag === "ITEM") { $this->item = TRUE; } } private function xmlCharacterData($parser, $data) { if ($this->item === TRUE) { // read the content tags switch ($this->tag) { case "TITLE": $this->title .= $data; break; case "DESCRIPTION": $this->description .= $data; break; case "LINK": $this->link .= $data; break; case "PUBDATE": $this->pubDate .= $data; break; } } } function xmlEndElement($parser, $tag) { if ($tag == 'ITEM') { $this->output[$this->counter]['title'] = trim($this->title); $this->output[$this->counter]['description'] = trim($this->description); $this->output[$this->counter]['link'] = trim($this->link); $this->output[$this->counter]['date'] = trim($this->pubDate); $this->counter++; $this->title = NULL; $this->description = NULL; $this->link = NULL; $this->pubDate = NULL; $this->item = FALSE; } } function __destruct() { } } ?>

One thought on “RSS Feed reader – simple PHP class

Comments are closed.