Your Ad Here

Posted By

TimoZachi on 09/10/11


Tagged

width video thumbnail api height duration YouTube


Versions (?)

Get All information from youtube video


 / 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.

  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. curl_close($ch);
  15.  
  16. //Using SimpleXML to parse youtube's feed
  17. $xml = simplexml_load_string($feed);
  18. $entry = $xml->entry[0];
  19. $media = $entry->children('media', true);
  20. $group = $media[0];
  21.  
  22. $title = $group->title;//$title: The video title
  23. $desc = $group->description;//$desc: The video description
  24. $vid_keywords = $group->keywords;//$vid_keywords: The video keywords
  25. $thumb = $group->thumbnail[0];//There are 4 thumbnails, The first is the largest.
  26. //$thumb_url: the url of the thumbnail. $thumb_width: thumbnail width in pixels.
  27. //$thumb_height: thumbnail height in pixels. $thumb_time: thumbnail time in the vi���­deo
  28. list($thumb_url, $thumb_width, $thumb_height, $thumb_time) = $thumb->attributes();
  29. $content_attributes = $group->content->attributes();
  30. //$vid_duration: the duration of the video in seconds. Ex.: 192.
  31. $vid_duration = $content_attributes['duration'];
  32. //$duration_formatted: the duration of the video formatted in "mm:ss". Ex.:01:54
  33. $duration_formatted = str_pad(floor($vid_duration/60), 2, '0', STR_PAD_LEFT) . ':' . str_pad($vid_duration%60, 2, '0', STR_PAD_LEFT);
  34.  
  35. //echoing the variables for testing purposes:
  36. echo 'title: ' . $title . '<br />';
  37. echo 'desc: ' . $desc . '<br />';
  38. echo 'video keywords: ' . $vid_keywords . '<br />';
  39. echo 'thumbnail url: ' . $thumb_url . '<br />';
  40. echo 'thumbnail width: ' . $thumb_width . '<br />';
  41. echo 'thumbnail height: ' . $thumb_height . '<br />';
  42. echo 'thumbnail time: ' . $thumb_time . '<br />';
  43. echo 'video duration: ' . $vid_duration . '<br />';
  44. echo 'video duration formatted: ' . $duration_formatted;
  45. ?>

Report this snippet  

You need to login to post a comment.