Wednesday, October 12, 2011

Using the YouTube API to Retrieve Top Rated Videos

One of the Zend Framework’s biggest strengths is its support for a wide variety of external API’s, especially Google’s. Using the Zend_Gdata component, you can read/write to a wide variety of Google applications, including Docs, Calendar, Spreadsheets, Health, and of course, YouTube. This article shows you how to retrive YouTube’s top rated videos using it’s API.
You do not need an API key or to perform account authorization to read any of the data from YouTube feeds. If you need to perform ‘write’ type operations on YouTube, you’ll need to login with valid credentials, which is covered in another article.

Zend Makes it Simple

All interaction with YouTube is handled with the Zend_Gdata_YouTube component, which provides you with a host of methods for interacting with YouTube. To get the top rated videos for a given time period, we’ll run the method getTopRatedVideoFeed(), which is extremely simple to use:





//Instantiate the YouTube object that provides access to YouTube API
$youtube = new Zend_Gdata_YouTube();
 
$feed = $youtube->getTopRatedVideoFeed();
Super simple! The variable $feed becomes an array of objects corresponding to the videos that YouTube returned.

Taking it Further

Suppose you want to specify the time frame for your top rated videos. This can be achieved by passing a VideoQuery object to the getTopRatedVideoFeed() method, as shown below.
 








//Instantiate the YouTube object
$youtube = new Zend_Gdata_YouTube();
 
$query = $youtube->newVideoQuery();
 
$query->setTime('today');
 
$feed = $youtube->getTopRatedVideoFeed($query);
Valid values for the time parameter passed to $query->setTime() are:
  • today
  • this_week
  • this_month
  • all_time
Note that most standard YouTube API queries, such as queries for the top rated, top favorites, most viewed, most popular, most discussed, most linked, and most responded all accept the time parameter.

No comments:

Post a Comment