nick cruse nick cruse - 1 year ago 64
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("[VIDOID]&key=[API KEY]");

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


This will return the time format something like this.


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

Answer Source

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]);