Developer Developer - 6 months ago 37
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:

$url = "". $vidID;
$doc = new DOMDocument;
$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
attribute this


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

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.


$url = "". $vidID;
$doc = new DOMDocument;
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
$duration = $doc->getElementsByTagName('duration')->item(0)->getAttribute('seconds');

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


TITLE: Introducing iTime
Duration: 29