YouTube API Tutorial: How To Get a Video’s Comments Using Raw PHP

This post is an alternative to a previous tutorial, YouTube API With Zend , where I showed you how to get a video’s comment using the Zend Framework.

In this post I will show you how to do the same thing but with built in PHP functions instead, let me know which you like best.

The Comment Feed URL

Each comment list is treated an individual feed, the URL format for each feed is the following.

http://gdata.youtube.com/feeds/api/videos/videoId/comments
YouTube Video ID

Video ID circled in red

How To Use This URL

If you copy and paste the following URL in your browser you will see the feed of comments for my BlueprintCSS video tutorial.

http://gdata.youtube.com/feeds/api/videos/KHLrEF9tHjw/comments

This means that you can parse the feed just like you would any RSS feed.

Optional Read: How to Read an RSS Feed With PHP

The Script to Parse The Comment Feed

// video id
$videoId='KHLrEF9tHjw';
// url where feed is located
$url="http://gdata.youtube.com/feeds/api/videos/{$videoId}/comments";
// get the feed
$comments=simplexml_load_file($url);
// parse the feed using a loop
foreach($comments->entry as $comment)
{
 echo '<fieldset>'.$comment->content.'</fieldset>';
}

The Result

Just like in the previous tutorial the result is the list of comments, each contained in a fieldset tag.

YouTube Video Comments

A Video's Comments

My Two Cents

Parsing feeds is easy with or without a framework but there are more things you can do with APIs, such as authenticating users or letting them upload videos, for which it will definitely be nice to not have to write the code from scratch.