Wednesday, 3 March 2010

PHP and Google Base API

So in order to learn about PHP and the Google Data API you need to know about the basic concepts of Google Base; in order to know about the basic concepts of Google Base you need to know about the Google Data API.

Cool, basically the Google Data API is all about HTTP requests and XML. XML is lovely and I know it, perhaps biblically ;-). HTTP requests I know less well but basically seem to me to be either GET or POST (GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT are all valid HTTP Request Methods (http://www.w3.org/Protocols/rfc2616/rfc2616.html)), but GET AND POST seem to me a lot like the Java thing of having setters and getters in order to access data within an object indirectly.

The following 3 things all do the same thing:

  1. http://www.google.com/base/feeds/snippets?bq=digital+camera%5Bitem%20type:products%5D%5Bprice%20%3C%20150%20USD%5D&max-results=10&orderby=modification_time
  2. http://www.google.com/base/feeds/snippets/-/products?bq=digital+camera%5Bprice%20%3C%20150%20USD%5D&max-results=10&orderby=modification_time
  3. <?php
      require_once 'Zend/Loader.php';  // this should point to your Zend lib installation
      Zend_Loader::loadClass('Zend_Gdata_Gbase');
    
      $service = new Zend_Gdata_Gbase();
    
      $query = $service->newSnippetQuery();
      $query->setCategory('products');
      $query->setBq('digital cameras[price < 150 USD]');
      $query->setMaxResults('10');
      $query->setOrderBy('modification_time');
    
      $feed = $service->getGbaseSnippetFeed($query);
    
      // Print our results
      foreach ($feed->entries as $entry) {
        echo '<p><b>' . $entry->title->text . '</b><br/>';
        echo '<small>' . $entry->id->text . '</small><br/>';
        echo $entry->content->text . "</p>";
      }
    ?>

If we break down the URIs above we get:

  1. http://www.google.com/base/feeds/snippets?bq=digital+camera%5Bitem%20type:products%5D%5Bprice%20%3C%20150%20USD%5D&max-results=10&orderby=modification_time
    which, once run through php's urldecode gets you:
    http://www.google.com/base/feeds/snippets
    ?bq=digital camera[item type:products][price < 150 USD]
    &max-results=10
    &orderby=modification_time
  2. http://www.google.com/base/feeds/snippets/-/products?bq=digital+camera%5Bprice%20%3C%20150%20USD%5D&max-results=10&orderby=modification_time
    which, once run through php's urldecode gets you:
    http://www.google.com/base/feeds/snippets/-/products
    ?bq=digital camera[price < 150 USD]
    &max-results=10
    &orderby=modification_time

Which both match the php code above nicely.