11

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?

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Developer
  • 2,676
  • 8
  • 43
  • 65

6 Answers6

17

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 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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris Rasco
  • 2,713
  • 1
  • 18
  • 22
  • 1
    This will stop working after API 2 deprecation on April 2015. Do you know an alternative solution? – Daniele B Feb 20 '15 at 16:14
  • Hi Daniele - Off hand I don't, but I'll take a look at it and see what I can find out. – Chris Rasco Feb 24 '15 at 02:36
  • 1
    @DanieleB I've updated my answer. I didn't dig into how to auth without user interaction with a browser, but the above code works with the new api. – Chris Rasco Feb 25 '15 at 04:47
11

Here it is YouTube API V3, with example of getting video duration, but do not forget to create your API key at https://console.developers.google.com/project

     $vidkey = "cHPMH2sa2Q" ; video key for example 
$apikey = "xxxxxxxxxxxxxxxxxxxxx" ;
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime) 
{
$VidDuration= $vidTime['contentDetails']['duration'];
}
Alaa Sadik
  • 1,029
  • 12
  • 19
3

A short and simple solution using SimpleXML:

function getYouTubeVideoDuration($id) {
 $xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/videos/'.$id);
 return strval($xml->xpath('//yt:duration[@seconds]')[0]->attributes()->seconds);
}
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
2

All the prev answers provide the duration in a text format:

This solution will give you the hours / minutes / seconds for you to transform to whatever format you would like:

function getDurationInSeconds($talkId){
   $vidkey = $talkId;
   $apikey = "xxxxx";
   $dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
   $VidDuration =json_decode($dur, true);
   foreach ($VidDuration['items'] as $vidTime)
   {
       $VidDuration= $vidTime['contentDetails']['duration'];
   }
   preg_match_all('/(\d+)/', $VidDuration, $parts);
   $hours = intval(floor($parts[0][0]/60) * 60 * 60);
   $minutes = intval($parts[0][0]%60 * 60);
   $seconds = intval($parts[0][1]);
   $totalSec = $hours + $minutes + $seconds; // This is the example in seconds
   return $totalSec;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nimrod007
  • 9,825
  • 8
  • 48
  • 71
0

Very easy

function getYoutubeDuration($videoid) {
      $xml = simplexml_load_file('https://gdata.youtube.com/feeds/api/videos/' . $videoid . '?v=2');
      $result = $xml->xpath('//yt:duration[@seconds]');
      $total_seconds = (int) $result[0]->attributes()->seconds;

      return $total_seconds;
}

//now call this pretty function. As parameter I gave a video id to my function and bam!
echo getYoutubeDuration("y5nKxHn4yVA");
hakki
  • 6,181
  • 6
  • 62
  • 106
-2

You can also get the duration in JSON

       $video_id = "<VIDEO_ID>";
       http://gdata.youtube.com/feeds/api/videos/$video_id?v=2&alt=jsonc

Oh! Sorry you can get it by:

$duration = $xml->getElementsByTagName('duration')->item(0)->getAttribute('seconds');
havefun
  • 33
  • 7