Parsing a FeedBurner feed with jQuery

Parsing a FeedBurner feed with jQuery requires two components:

  1. a proxy to fetch the feed
  2. Ajax to parse the feed

Here's the proxy, written in PHP:

<?php
header('Content-Type: text/xml');

$feed = file_get_contents('http://feeds.feedburner.com/blogspot/onwebdev/');

echo $feed;

?>

Now we can add jQuery:

$(document).ready(function() {
    
        $('<ul></ul>').insertAfter('h1');
    
    
        $.get('proxy.php', function(data) {
        
        
            var $items = $(data).find('item');
            
            $items.each(function() {
            
                var html = '';
            
                var $item = $(this);
                
                var $title = $item.find('title').text();
                var raw_author = $item.find('author').text();
                
                var $author = raw_author.replace('gabriele.romanato@gmail.com', '').
                              replace('(', '').replace(')', '');
                              
                var $link = $item.find('author').next().next().text();
                
                var raw_date = $item.find('pubDate').text();
                var $pubdate = raw_date.replace('+0000', '');
                
                
                html += '<li><a href="' + $link + '">' + $title + '</a>' + '<div class="author">' + $author + '</div>' + 
        '<div class="pubdate">' + $pubdate + '</div>' + "</li>";

                $(html).appendTo('ul');
            
            });
        
        
        
        });
    
    
    });

There's only a difficult part here: selecting the feedburner:origLink element which has a namespace. To accomplish this task, we've used the next() method which returns the adjacent sibling of a given element. You can see the final result here.

Parsing a FeedBurner feed with SimpleXML

Parsing a FeedBurner feed with SimpleXML requires only a single gotcha: the actual parsing starts from the root element, not from the whole object created with the simplexml_load_file() function. For example, the following code returns nothing:

$feed = simplexml_load_file('http://feeds.feedburner.com/blogspot/onwebdev/');

foreach($feed->item as $item) {

    //... nothing here

}

Instead, the following code works as expected:

 $feed = simplexml_load_file('http://feeds.feedburner.com/blogspot/onwebdev/');
    
    foreach($feed->channel->item as $item) {
    
        $title = $item->title;
        $raw_author = $item->author;
        $author = str_replace('gabriele.romanato@gmail.com', '', $raw_author);
        $author = str_replace('(', '', $author);
        $author = str_replace(')', '', $author);
        $links = $item->children('http://rssnamespace.org/feedburner/ext/1.0');
        $link = $links->origLink;
        $raw_date = $item->pubDate;
        $pubdate = str_replace('+0000', '', $raw_date);
        
        echo '<li><a href="' . $link . '">' . $title . '</a>' . "\n" . '<div class="author">' . $author . '</div>' . "\n" .
        '<div class="pubdate">' . $pubdate . '</div>' . "</li>\n";
    
    
    }

You can notice that now the parsing starts from the channel element. You can see the final result here.

XML structure of a FeedBurner feed

A FeedBurner feed is usually located at the address you've chosen as your FeedBurner account name. For example, my FeedBurner feed is located at http://feeds.feedburner.com/blogspot/onwebdev. If you use a download command line utility (such as wget), you can download it very easily. Basically, this kind of feed is automatically generated by a server-side script, so you can stumble on some problems if you try to fetch this resource from your website. In my case, I've tried to use PHP's DOM extension and SimpleXML to parse my feed, but it didn't work, because this kind of approach requires the presence of a static XML file. Nevertheless, if you use a more common stream-based approach (like file_get_contents()), it works fine, though.

In any case, you need to know in advance the structure of a FeedBurner feed if you want to succeed. In this post, we'll look into the details of this kind of feed.

Root element and namespaces

<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

The root element is rss with five namespaces attached to it. The namespaces are:

  1. atom: http://www.w3.org/2005/Atom
  2. openSearch: http://a9.com/-/spec/opensearch/1.1/
  3. georss: http://www.georss.org/georss
  4. thr: http://purl.org/syndication/thread/1.0
  5. feedburner: http://rssnamespace.org/feedburner/ext/1.0

Many of the elements that we'll find within our feed belong to one or more of these namespaces, so it must be clear from start that we have to take these namespaces into account while parsing our feed. Either we choose a server-side approach or a client-side one, if we don't know very well the namespace structure of our feed, it's more likely that we'll encounter some problems.

The channel element

The channel element contains both item elements and some additional information that we may use to add some description to our feed. Basically, the elements directly contained within the channel element that are relevant for our purpose are:

  1. title: the title of the whole feed
  2. description: a brief description of our feed
  3. link: the URI of our blog or website
  4. lastBuildDate: a date of the latest updates to our feed
  5. managingEditor: the author of the feed.

But the most important element of the channel element is surely item. It's discussed below.

The item element

Each item element contains the relevant information about a post of our blog or website. The most important children of this element are:

  1. pubDate: the date when our post has been published
  2. category: the category under which our post has been published (one or more elements)
  3. title: the title of our post
  4. description: the content of our post; XHTML tags are inserted by encoding the < and > entities, such as &lt; and &gt;
  5. feedburner:origLink: the original link of your post
  6. author: the author of the post

We've only one problem here: the feedburner:origLink belongs to our feedburner global namespace, so we have to take this aspect into account during parsing. Basically, you have to select an element that "lives" inside the feedburner global namespace. The most obvious solution to this problem is using a DOM method such as getElementsByTagNameNS(). or, if you use SimpleXML or any other string-based extension, an approach like this:

$link_ns = $item->children('http://rssnamespace.org/feedburner/ext/1.0');
$link = $link_ns->origLink;

For more info on this solution, read this article.

Redirecting Wordpress feeds to FeedBurner with PHP

I just finished to read the following mini tutorial from WPBeginner:

Recently we featured an article that showed a step by step guide to setup FeedBurner in which we shared the plugins you can use to redirect. In this article, we will show you how you can redirect WordPress RSS Feeds to Feedburner without using a plugin (This tip is for intermediate to advanced users).

First open your .htaccess file which is located in your root directory (Hint: same folder where wp-config.php is located). Then paste the following code:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} !FeedBurner [NC]
RewriteCond %{HTTP_USER_AGENT} !FeedValidator [NC]
RewriteRule ^feed/?([_0-9a-z-] )?/?$ http://feeds.feedburner.com/wpbeginner [R=302,NC,L]
</IfModule>

By the way, don’t forget to change the feed URL to your own Feed URL otherwise you will be redirecting users to our Feeds.

I don't think this is a good idea and for one simple reason: performance. .htaccess files are processed by Apache every time that a certain directory is requested by a client. The more declarations you have inside an .htaccess file, the more the server will spend its resources to serve a given request. This is something that you can do by simply using PHP. What we've got so far? We have:

  1. a directory where our feeds are located (in this case /feed)
  2. a FeedBurner URL where to redirect our requests.

You have to create a simple PHP function to be used when an user requests our feed directory:

function redirectFeed()

{

$feed_request = $_SERVER['HTTP_REQUEST'];
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);

if(!preg_match('/feedburner|feedvalidator/', $ua) {

    if(preg_match('/feed/.+/', $feed_request)) {
    
        header('Location: http://feeds.feedburner.com/yourfeed');
    
    }

}

}

Simply insert this function in an empty Wordpress page template when you need to perform such a redirect.

Note

Please test the above code before using it. I didn't test it myself simply because I don't use Wordpress on this blog.