FeedParser: A PHP Class for Quick Feed Parsing

Well, it doesn’t require any further explanation — we the web developers know how often we need to parse feeds. It’s a very common practice to use SimpleXML for parsing feeds. But today Hasin vai (Hasin Hayder) showed me a very cool thing — the Google Feed Parser. It’s a web based feed parser that is internally used by Google. The coolest thing about the parser is that it returns data as JSON :)

Seeing the point, I quickly fired off my netbeans IDE and wrote a php class for quick feed parsing :D Why fetch the feed and then parse it? Let Google handle the parsing and fetch the parsed results :) Google is really making our lives simpler!

Here’s the class definition:

 
<?php
// Filename: feedparser.php
class FeedParser {
    function parse($feedUrl="http://masnun.com/feed/rss/",$number=5) {
        $feedUrl = urlencode($feedUrl);
        $gUrl = "http://www.google.com/uds/Gfeeds?num={$number}&hl=en&output=json&q={$feedUrl}&v=1.0";
        $json = json_decode(file_get_contents($gUrl),true);
        return  $json["responseData"]["feed"];
    }
}
?>

So, how do you use it? Initiate a new FeedParser object and then call the parse() method with the feed URL and entry count. The second parameter is optional and is “5″ by default.

 
<?php
include("feedparser.php");
$parser = new FeedParser();
$data = $parser->parse("http://masnun.com/feed/rss/",3);
echo  $data["entries"][2]['title']."\n";
?>

So what do we get in the $data array? Good question, lets see :

 
<?php
include("feedparser.php");
$parser = new FeedParser();
$data = $parser->parse("http://masnun.com/feed/rss/",3);
var_dump( $data );
?>
This entry was posted in Blog Post and tagged . Bookmark the permalink.

One Response to FeedParser: A PHP Class for Quick Feed Parsing

  1. Pingback: FeedParser: A PHP Class for Quick Feed Parsing | maSnun.com | Coder Online

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">