Trackbacks with Google Blog Search and Zend Feed

I’ve wanted to do automatic trackbacking by linking to posts that are linking to any given article of mine, for quite some time now.

At first I looked at Technorati, but no, max 500 requests on a blog getting almost 2000 hits per day, thanks but no thanks.

So Google Blog Search it is then. When you use the search you have the option of subscribing to it through an RSS feed. I did a link:url search and just copied the resultant feed URL. Using this URL it is possible to fetch for instance 10 results and display them through parsing the atom feed.

A recent article where the functionality can be seen is CRUD with Doctrine. Scroll down to the end of the article and you will see the list above the comment section.

set_include_path('../PEAR' . PATH_SEPARATOR . get_include_path());

$url    = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$search = "$url&ie=utf-8&output=atom";

$feed = Zend_Feed::import($search);

$count = 0;

if($feed->count() > 0){
  echo '<h4>Posts linking to this article:</h4>';
  foreach($feed as $item) {
    echo '<a href="'.$item->link('alternate').'" rel="nofollow">'.$item->title().'</a><br/>'.
    if($count > 10) break;
  echo '<a href="'.$url.'%26ie%3Dutf-8%26output%3Datom" rel="nofollow">Subscribe with Google Reader</a>';

So we establish a runtime include path to our PEAR folder were we have put the Zend folder.

We load Zend Feed and the Atom extension. The URL to use will be the full path to the current article, after we get it from the SERVER global we put it into the Google search query.

We import the feed and start looping through it.

Note the use of $item->link(‘alternate’), atom feeds will have the link as an href attribute with a rel attribute of alternate. Passing this to the link method will for some reason make Zend return the href attribute. I had to check the source code to figure that one out, not really intuitive.

Had we had a normal RSS2 feed we would manage with simply calling link() without any arguments.

And finally as a kickback to Google for making this awesome service without any silly caps I put the link to subscribing with Google Reader at the bottom.

Related Posts

Tags: , , , , ,