/ Published in: PHP
This code snippet gets all information from a YouTube video (title, description, duration, thumbnail url, thumbnail width, thumbnail height, etc..) using the video id and YouTube API.
Expand |
Embed | Plain Text
<?php //The Youtube's API url //Change below the video id. $video_id = '66Wi3isw3NY'; //Using cURL php extension to make the request to youtube API $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, YT_API_URL . $video_id); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //$feed holds a rss feed xml returned by youtube API $feed = curl_exec($ch); curl_close($ch); //Using SimpleXML to parse youtube's feed $xml = simplexml_load_string($feed); $entry = $xml->entry[0]; //If no entry whas found, then youtube didn't find any video with specified id if(!$entry) exit('Error: no video with id "' . $video_id . '" whas found. Please specify the id of a existing video.'); $media = $entry->children('media', true); $group = $media->group; $title = $group->title;//$title: The video title $desc = $group->description;//$desc: The video description $vid_keywords = $group->keywords;//$vid_keywords: The video keywords $thumb = $group->thumbnail[0];//There are 4 thumbnails, the first one (index 0) is the largest. //$thumb_url: the url of the thumbnail. $thumb_width: thumbnail width in pixels. //$thumb_height: thumbnail height in pixels. $thumb_time: thumbnail time in the video $content_attributes = $group->content->attributes(); //$vid_duration: the duration of the video in seconds. Ex.: 192. $vid_duration = $content_attributes['duration']; //$duration_formatted: the duration of the video formatted in "mm:ss". Ex.:01:54 //echoing the variables for testing purposes: ?>
Comments
Subscribe to comments
You need to login to post a comment.

Hi! Why am I getting this error only sometimes? Fatal error: Call to a member function children() on a non-object
Zoltan, the reason the error message appeared it's probably because the video id you used isn't a valid youtube id (there are no videos with that id). You need to specify an EXISTENT video id. I've updated the snippet so that it shows a more descriptive error message in case that happens again. Sry bad english.
Zoltan, the reason the error message appeared it's probably because the video id you used isn't a valid youtube id (there are no videos with that id). You need to specify an EXISTENT video id. I've updated the snippet so that it shows a more descriptive error message in case that happens again. Sry bad english.
It seems that I had problems with internet connection, now works fine. Thanks a lot for answer and thank you for code update!