21 May, 2010

Get Most Viewed YouTube Videos Using PHP

The following code is used to get most viewed youtube videos using php. I've used simplexml for
processing the response that we get from the youtube feed url for most vewed youtube videos.
I then go through each of the entry element of response using foreach method. The code provides details cush as
author name, length of video, total views, favorites count, thumbnial image, url of the video, etc.

//code to get most viewed videos using php with youtube api
//the feed url for most viewed youtube videos
$url = 'http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed';
$xml = simplexml_load_file($url);
//the entry tag of most viewed videos in youtube contains video name, title, category, description, etc kind of information
foreach($xml->entry as $item) {
//nodes inside media; the media rss url
$media = $item->children('http://search.yahoo.com/mrss/');

//get the title of video
$videoTtitle = $media->group->title;

//get the thumbnail of video
//as more than one image exists so we just need the first image so
$thumbAtt = $media->group->thumbnail[0]->attributes();
$thumbUrl = $thumbAtt['url'];

//get the url of video player --> $playerAtt = $media->group->player->attributes();
$videoUrl = $playerAtt['url'];

//get the total views and total favorites for the video , inside yt tag
$yt = $item->children('http://gdata.youtube.com/schemas/2007');

//get the statistics attributes
$statAtt = $yt->statistics->attributes();
//total video views count
$totalViews = $statAtt['viewCount'];
//total favorites count for the video
$totalFavs = $statAtt['favoriteCount'];


//get the total length of video -- yt tag again
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$lengthAtt = $yt->duration->attributes();
//total video length in seconds
$videoLength = $lengthAtt['seconds'];

//get the name of user who posted the video
$authorName = $item->author->name;
} //end of foreach

?>

After getting all the values for most viewed videos using php you can easily format it and display on your site.

No comments: