Get All information from youtube video


/ Published in: PHP
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. <?php
  2. //The Youtube's API url
  3. define('YT_API_URL', 'http://gdata.youtube.com/feeds/api/videos?q=');
  4.  
  5. //Change below the video id.
  6. $video_id = '66Wi3isw3NY';
  7.  
  8. //Using cURL php extension to make the request to youtube API
  9. $ch = curl_init();
  10. curl_setopt($ch, CURLOPT_URL, YT_API_URL . $video_id);
  11. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  12. //$feed holds a rss feed xml returned by youtube API
  13. $feed = curl_exec($ch);
  14.  
  15. //Using SimpleXML to parse youtube's feed
  16. $xml = simplexml_load_string($feed);
  17.  
  18. $entry = $xml->entry[0];
  19. //If no entry whas found, then youtube didn't find any video with specified id
  20. if(!$entry) exit('Error: no video with id "' . $video_id . '" whas found. Please specify the id of a existing video.');
  21. $media = $entry->children('media', true);
  22. $group = $media->group;
  23.  
  24. $title = $group->title;//$title: The video title
  25. $desc = $group->description;//$desc: The video description
  26. $vid_keywords = $group->keywords;//$vid_keywords: The video keywords
  27. $thumb = $group->thumbnail[0];//There are 4 thumbnails, the first one (index 0) is the largest.
  28. //$thumb_url: the url of the thumbnail. $thumb_width: thumbnail width in pixels.
  29. //$thumb_height: thumbnail height in pixels. $thumb_time: thumbnail time in the video
  30. list($thumb_url, $thumb_width, $thumb_height, $thumb_time) = $thumb->attributes();
  31. $content_attributes = $group->content->attributes();
  32. //$vid_duration: the duration of the video in seconds. Ex.: 192.
  33. $vid_duration = $content_attributes['duration'];
  34. //$duration_formatted: the duration of the video formatted in "mm:ss". Ex.:01:54
  35. $duration_formatted = str_pad(floor($vid_duration/60), 2, '0', STR_PAD_LEFT) . ':' . str_pad($vid_duration%60, 2, '0', STR_PAD_LEFT);
  36.  
  37. //echoing the variables for testing purposes:
  38. echo 'title: ' . $title . '<br />';
  39. echo 'desc: ' . $desc . '<br />';
  40. echo 'video keywords: ' . $vid_keywords . '<br />';
  41. echo 'thumbnail url: ' . $thumb_url . '<br />';
  42. echo 'thumbnail width: ' . $thumb_width . '<br />';
  43. echo 'thumbnail height: ' . $thumb_height . '<br />';
  44. echo 'thumbnail time: ' . $thumb_time . '<br />';
  45. echo 'video duration: ' . $vid_duration . '<br />';
  46. echo 'video duration formatted: ' . $duration_formatted;
  47. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.