PHP Script: Simple RSS Parser Class

A while back I wrote up a quick PHP script for RSS parsing. Earlier today I decided to wrap it in a nice easily-customizable class. You can see it in action here. You can either download the code here or just copy and paste it from below:

<?php

class RSSParser {

	var $insideitem = false;
	var $tag = "";
	var $title = "";
	var $description = "";
	var $link = "";

	var $num = 0;
	var $before_item = "<li>"; //default before
	var $after_tem = "</li>"; //default after
	
	function startElement($parser, $name, $attrs) {
		if($this->insideitem) {
			$this->tag = $name;
		} 
		else if($name == "ITEM") {
			$this->insideitem = true;
		}
	}

	function endElement($parser, $name) {	
		if ($name == "ITEM") {
			printf("$this->before_item<a href='%s'>%s</a>$this->after_tem",trim($this->link),htmlspecialchars(trim($this->title)));
			$this->title = "";
			$this->description = "";
			$this->link = "";
			$this->insideitem = false;
			$this->num++;
		}
	}

	function characterData($parser, $data) {
		if($this->insideitem) {
			switch($this->tag) {
				case "TITLE":
					$this->title .= $data;
					break;
				case "DESCRIPTION":
					$this->description .= $data;
					break;
				case "LINK":
					$this->link .= $data;
					break;
			}
		}
	}
	
	
	function RSSParser($feed,$numitems,$before = "<li>",$after = "</li>") {	
		$this->num = 0;
		$this->before_item = $before;
		$this->after_item = $after;
	
		$xml_parser = xml_parser_create();
	
	
		xml_set_object ($xml_parser, $this );
		xml_set_element_handler($xml_parser, "startElement", "endElement");
		xml_set_character_data_handler($xml_parser, "characterData");
	
		$fp = fopen($feed,"r") or die("Error reading RSS data. Click <a href=$feed>here</a> to view it (with rss reader).");
	
		while (($data = fread($fp, 4096)) && ($this->num < $numitems)) {
			xml_parse($xml_parser, $data, feof($fp)) or die("Error parsing RSS data. Click <a href=$feed>here</a> to view it (with rss reader).");
		}
	
		fclose($fp);
	
		xml_parser_free($xml_parser);
	}
}

?>

<html>
<body>
<ul>
<?php

$parser = new RSSParser("http://feeds.feedburner.com/Nusuni/",10); //default vals for before and after are <li> and </li>, no need to enter them
?>
</ul>
</body>
</html>

Please subscribe, or else I will cry. Do you really want to make a programmer cry?

Leave a Reply

Note: By submitting your comment you agree to this blog's comment policy.

If you want a little icon next to your name - sign up for one at Gravatar.