Get duration from a youtube url

Pollux Khafra picture Pollux Khafra · Feb 6, 2012 · Viewed 21.2k times · Source

Im looking for a function that will pull the youtube duration of a video from the url. I read some tutorials but don't get it. I embed videos on my site using a url and I have a function that pulls the thumbnail and I just want something similar that gets the duration. Here's how I get the thumb...

function get_youtube_screen_link( $url = '', $type = 'default', $echo = true ) {
if( empty( $url ) )
    return false;

if( !isset( $type ) )
    $type = '';

$url = esc_url( $url );

preg_match("|[\\?&]v=([^&#]*)|",$url,$vid_id);

if( !isset( $vid_id[1] ) )
    return false;

$img_server_num =  'i'. rand(1,4);

switch( $type ) {
    case 'large':
        $img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/0.jpg";
        break;
    case 'first':
        // Thumbnail of the first frame
        $img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/1.jpg";
        break;
    case 'small':
        // Thumbnail of a later frame(i'm not sure how they determine this)
        $img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/2.jpg";
        break;
    case 'default':
    case '':
    default:
        $img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/default.jpg";
        break;
}
if( $echo )
    echo $img_link;
else
    return $img_link;

}

Answer

stewe picture stewe · Feb 6, 2012

You could use something like this:

<?php

    function getDuration($url){

        parse_str(parse_url($url,PHP_URL_QUERY),$arr);
        $video_id=$arr['v']; 


        $data=@file_get_contents('http://gdata.youtube.com/feeds/api/videos/'.$video_id.'?v=2&alt=jsonc');
        if (false===$data) return false;

        $obj=json_decode($data);

        return $obj->data->duration;
    }

    echo getDuration('http://www.youtube.com/watch?v=rFQc7VRJowk');

?>

that returns the duration in seconds of the video.

Reference: http://code.google.com/apis/youtube/2.0/developers_guide_protocol.html

You can use a function like this one to change the seconds to hours, minutes, and seconds.