YouTube API With Zend Framework Tutorial, Installation

Today I want to show you how to use the Zend Framework to work YouTube’s API. While there isn’t anything you can’t do without the framework it sure makes you code a lot shorter, less error prone and you can take advantage some other functionalities such as caching that this framework offers.

What You Need To Get Started

The only tool you need to start using YouTube’s API is the Zend Framework.

I have written a tutorial with info on where to download and how to install the framework here.

How to install Zend

Zend Framework Logo

Zend Framework Version 1.10 Logo

How To Work With The Framework

The class you are going to need from Zend to work with YouTube is called “Zend_Gdata_YouTube”. In Zend each dash in the class’ name separates directories where the class is located, so to include this class in your script you would have to do the following.

require_once 'Zend/Gdata/YouTube.php'; // includes the class Zend_Gdata_YouTube

Now make an object of this class, its constructor does not require parameters.

// include the class
require_once 'Zend/Gdata/YouTube.php';
// make an object of the class
$youtube=new Zend_Gdata_YouTube();

Retrieving Video Comments

Getting a video’s comments is a lot easier with Zend than with raw PHP.

The first thing you need is a video’s ID. The ID is the value of the "v" parameter in a video’s URL.

YouTube Video ID

Video ID circled in red

Mobile Development Tutorials

The function you will use to get the comments from a video is called getVideoCommentFeed(), and its parameter is a video id. This function returns the comment feed which you can then go through with a loop.

Your script so far:

// include the class
require_once 'Zend/Gdata/YouTube.php';
// make a youtube object
$youtube=new Zend_Gdata_YouTube();
// video id
$videoId='KHLrEF9tHjw';
// get comment feed
$commentFeed = $youtube->getVideoCommentFeed($videoId);

You can see what the variable $commentFeed has in it by doing the following.

echo '<pre>';
var_dump($commentFeed);
echo '</pre>';

Looping Through The Comment Feed

Each comment’s text is located under "content" and in "text" in your $commentFeed array.

Think of it like this structure.

<comment>
	<content>
		<text>
			First!
		 </text>
	</content>
</comment>
<comment>
	<content>
		<text>
			Great video!
		 </text>
	</content>
</comment>

<comment>
	<content>
		<text>
			This video sucks...
		 </text>
	</content>
</comment>

I like to use foreach loops whenever I can, they make the code more readable in my opinion. Here is the loop you need to go through the comments.

foreach($commentFeed as $comment)
{
 echo '<fieldset>'.$comment->content->text.'</fieldset>';
}

The Result

If it all went well you should a bunch comments wrapped in boxes like this.

YouTube Video Comments

A Video's Comments

blog comments powered by Disqus