Developer Developer - 4 months ago 26
PHP Question

How to get video duration using YouTube API?

I want to get the duration of a Youtube video. Here's the code I tried:

$vidID="voNEBqRZmBc";
//http://www.youtube.com/watch?v=voNEBqRZmBc
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID;
$doc = new DOMDocument;
$doc->load($url);
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;


Please check the XML file. I got the title of this video. I want to get duration from
<yt:duration seconds='29'/>
.

How to get the
seconds
attribute this
<yt>
tag?

Answer

Due to the upcoming deprecation of the Youtube v2 API, here is an updated solution.

  1. Start by cloning the Google API PHP Client here
  2. Next, you'll want to register an application with Google here by creating a new Project, turning on the Youtube Data API under the "APIs and auth > API" section, and
  3. Create a new OAuth Client ID under "APIs and auth > Credentials" and add the full path to your redirect uri list. (i.e. http://example.com/get_youtube_duration.php)
  4. Use this code (which was adapted from this sample code), while making sure to fill in the $OAUTH2_CLIENT_ID and $OAUTH2_CLIENT_SECRET variables with your own values from step 3.
  5. Hardcode a value for the $videoId variable or set it using the video_id get parameter (i.e. http://example.com/get_youtube_duration.php?video_id=XXXXXXX)
  6. Visit your script, click the link to authorize the app and use your google account to get a token, which redirects you back to your code and will display the duration.

Here is your output:

Video Duration

0 mins

29 secs

Some additional resources: https://developers.google.com/youtube/v3/docs/videos#contentDetails.duration https://developers.google.com/youtube/v3/docs/videos/list

The following works for the V2 API only.

This worked for me based on the assumption that there is only 1 duration element in the feed.

<?php

$vidID="voNEBqRZmBc";
//http://www.youtube.com/watch?v=voNEBqRZmBc
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID;
$doc = new DOMDocument;
$doc->load($url);
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
$duration = $doc->getElementsByTagName('duration')->item(0)->getAttribute('seconds');

print "TITLE: ".$title."<br />";
print "Duration: ".$duration ."<br />";

Output:

TITLE: Introducing iTime
Duration: 29
Comments