nick cruse nick cruse - 4 months ago 19
PHP Question

Get duration using YouTube API

I need to get the video duration using Youtube API V3. My application was working fine with API V3 but now i doesn't work

I found a working example and it works.

$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=[VIDOID]&key=[API KEY]");


$duration =json_decode($dur, true);
foreach ($duration['items'] as $vidTime) {
$vTime= $vidTime['contentDetails']['duration'];
}


Credits:
http://stackoverflow.com/questions/15596753/youtube-api-v3-how-to-get-video-durations


This will return the time format something like this.

PT24M30S


How can i convent this in to readable time. above in to 24:30?

Answer

One possible way is to use the function str_replace();

$stamp = "PT24M30S";
$formated_stamp = str_replace(array("PT","M","S"), array("",":",""),$stamp);

echo $formated_stamp; //should give "24:30"

Bonus content - leading zeros

In order to add leading zeros one must first split the string up with explode(), then format the numbers idividually with sprintf(); and finally add it all together again.

$exploded_string = explode(":",$formated_stamp);
$new_formated_stamp = sprintf("%02d", $exploded_string[0]).":".sprintf("%02d", $exploded_string[1]);