PHP get a Youtube video duration

To make this work you need to go to Google Developers Console, create a project, enable the YouTube Data API v3, and get a key in authentication key in credentials. This is pretty much the difficult part.

Now the easy part, so easy and keystroke economic to do this in PHP… just a couple of lines, and it’s done:

define("API_KEY", ""); // Fill in your Google API Key
function getYoutubeDurationV3($id) { 
  $json = json_decode(

  $start   = new DateTime('@0');
  $youtube = new DateTime('@0'); 
  $youtube->add(new DateInterval($json->items[0]->contentDetails->duration));
  return $youtube->getTimestamp() - $start->getTimestamp();

This point downwards is for archive only, the v2 API has been shut down since April 2015

function getYoutubeDuration($id) {
    $xml = simplexml_load_file(''.$id.'?v=2);
    $result = $xml->xpath('//yt:duration[@seconds]');
    $total_seconds = (int) $result[0]->attributes()->seconds;

    return total_seconds;

There, done, solved. Next…

6 thoughts on “PHP get a Youtube video duration”

Leave a Reply