We can use a PHP function to get the YouTube video duration.
Before that, you should have Google API Key
1.Create Google API and get API key from Goog’s official website https://console.developers.google.com
One important Note.
At the time of creating API, leave the below option blank
” Accept requests from these HTTP referrers (web sites) (Optional)”.
So your requests will be accepted from any referrer.
API demands more security then add referrers before using API key in production.
Example: *.example.com/*
CodIng Hint: Place the PHP tags before and after the PHP function.
function getYoutubeDuration($vid) {
$videoDetails = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=".$vid."&part=contentDetails,statistics&key=AIzaSyDen99uTRRPl9VT_Ra9eAisvZSc4aZDEns");
$videoDetails =json_decode($videoDetails, true);
foreach ($videoDetails['items'] as $vidTime)
{
$youtube_time = $vidTime['contentDetails']['duration'];
preg_match_all('/(d+)/',$youtube_time,$parts);
$hours = (strlen(floor($parts[0][0]/60))<1)?floor($parts[0][0]/60):'0'.floor($parts[0][0]/60);
$minutes = $parts[0][0]%60; (strlen($parts[0][0]%60)<1)?$parts[0][0]%60:'0'.$parts[0][0]%60;
$seconds = $parts[0][1];(strlen($parts[0][1])<1)?$parts[0][1]:'0'.$parts[0][1];
return 'Duration'.$hours.":".$minutes.":".$seconds;
}
}
echo getYoutubeDuration('wwAvoi2TDOk');//Youtube Video ID-wwAvoi2TDOk
Output
Duration:00:1:54
If you have any doubt or error, don’t hesitate to email me
Also, Look on
How to create thumbnails from youtube video
we use second not fetch