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( file_get_contents('https://www.googleapis.com/youtube/v3/videos'. '?part=contentDetails&d='.$id.'&key='.API_KEY) ); $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('https://gdata.youtube.com/feeds/api/videos/'.$id.'?v=2); $result = $xml->xpath('//yt:duration[@seconds]'); $total_seconds = (int) $result[0]->attributes()->seconds; return total_seconds; }
There, done, solved. Next…