Due to the upcoming deprecation of the YouTube v2 API, here is an updated solution.
- Start by cloning the Google API PHP Client here
- 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
- 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)
- 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.
- 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)
- 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 one 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