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…
Might Be silly but what is id suppossed to be here ?
Every youtube video has an unique IDentifier. For example:
https://www.youtube.com/watch?v=Q4wb11w0ZHQ
The id is Q4wb11w0ZHQ
PS – actually the code in the post is obsolete since the Youtube API v2 has been shutdown. Will update the post has soon as possible
not work with me
Check your Google API and API permissions
How can I echo the final result?
echo getYoutubeDurationV3($id);