Get duration from a youtube url
Asked Answered
S

7

11

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;

}

Spider answered 6/2, 2012 at 21:21 Comment(0)
B
13

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.

Bil answered 6/2, 2012 at 21:47 Comment(6)
I need the $video_id to to pull it from the url entered into a custom field for each post.Spider
Updated the example to get the video_id from urlBil
I used this as a function and it works but if a video has been removed from youtube then I get errors where it tries to output. How can I make an if statement to protect against that?Spider
Updated the example to return false if video doesn't exist.Bil
Thanks for your time and workin me through that! Works perfectly.Spider
This endpoint is no longer available, you have to use the youtube v3 api now.Carillon
S
5

youtube api v3


usage

echo youtubeVideoDuration('video_url', 'your_api_key');
// output: 63 (seconds)

function

/**
* Return video duration in seconds.
* 
* @param $video_url
* @param $api_key
* @return integer|null
*/
function youtubeVideoDuration($video_url, $api_key) {

    // video id from url
    parse_str(parse_url($video_url, PHP_URL_QUERY), $get_parameters);
    $video_id = $get_parameters['v'];

    // video json data
    $json_result = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$video_id&key=$api_key");
    $result = json_decode($json_result, true);

    // video duration data
    if (!count($result['items'])) {
        return null;
    }
    $duration_encoded = $result['items'][0]['contentDetails']['duration'];

    // duration
    $interval = new DateInterval($duration_encoded);
    $seconds = $interval->days * 86400 + $interval->h * 3600 + $interval->i * 60 + $interval->s;

    return $seconds;
}
Shannon answered 4/6, 2015 at 7:1 Comment(2)
doesn't work for me , says file_get_content is blocked for security reasonsRestricted
NOT api_key, you should use "key".Firstclass
W
4

This is my function to get youtube duration in second. he is fully 100% work. you need just youtube id video and youtube api key.

how to add youtube api key show this video https://www.youtube.com/watch?v=4AQ9UamPN6E

public static function getYoutubeDuration($id)
    {



         $Youtube_KEY='';

         $dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id={$id}&key={$Youtube_KEY}");

         $vTime='';
         $H=0;
         $M=0;
         $S=0;

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

         $vTime = substr($vTime, 2);
         $exp = explode("H",$vTime);

         //if explode executed
         if( $exp[0] != $vTime )
         {
             $H = $exp[0];
             $vTime = $exp[1];
         }

         $exp = explode("M",$vTime);

         if( $exp[0] != $vTime )
         {
             $M = $exp[0];
             $vTime = $exp[1];
         }

         $exp = explode("S",$vTime);
         $S = $exp[0];


         $H = ($H*3600);
         $M = ($M*60);
         $S = ($H+$M+$S);


         return $S;

    }

This is my function to get youtube duration in second. he is fully 100% work. you need just youtube id video and youtube api key.

how to add youtube api key show this video https://www.youtube.com/watch?v=4AQ9UamPN6E

Weisburgh answered 23/7, 2017 at 17:49 Comment(0)
D
0

You can simply use a time formater to change the seconds into whatever format you like. i.e. return gmdate("H:i:s", $obj->data->duration);

Dee answered 11/6, 2013 at 4:58 Comment(0)
U
0
function getYoutubeDuration($videoid) {
      $xml = simplexml_load_file('https://gdata.youtube.com/feeds/api/videos/' . $videoid . '?v=2');
      $result = $xml->xpath('//yt:duration[@seconds]');
      $total_seconds = (int) $result[0]->attributes()->seconds;

      return $total_seconds;
}

//now call this pretty function. 
//As parameter I gave a video id to my function and bam!
echo getYoutubeDuration("y5nKxHn4yVA");
Unni answered 19/7, 2014 at 21:37 Comment(0)
M
0

1) You will need an API key. Go to https://developers.google.com/ and log in or create an account, if necessary. After logging in go to this link https://console.developers.google.com/project and click on the blue CREATE PROJECT button. Wait a moment as Google prepares your project.

2) You will need a web host that is running PHP with file_get_content supported. You can check by creating a new script with just "echo php_info();" and verifying that allow_url_fopen is set to On. If it is not, then change the configuration or talk to your web host.

<?php

  $sYouTubeApiKey = "<enter the key you get>";
  //Replace This With The Video ID. You can get it from the URL.
  //ie https://www.youtube.com/XWuUdJo9ubM would be
  $sVideoId = "XWuUdJo9ubM";

  //Get The Video Details From The API.
  function getVideoDetails ($sVideoId) {
    global $sYouTubeApiKey;
    //Generate The API URL
    $sUrl = "https://www.googleapis.com/youtube/v3/videos?id=".$sVideoId."&key=".$sYouTubeApiKey."&part=contentDetails";
    //Perform The Request
    $sData = file_get_contents($sUrl);
    //Decode The JSON Response
    return json_decode($sData);
  }

  //Get The Video Duration In Seconds.
  function getVideoDuration ($sVideoId) {
    $oData = getVideoDetails($sVideoId);
    //Deal With No Videos In List
    if (count($oData->items) < 1) return false;
    //Get The First Video
    $oVideo = array_shift($oData->items);
    //Extract The Duration
    $sDuration = $oVideo->contentDetails->duration;
    //Use Regular Expression To Parse The Length
    $pFields = "'PT(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?'si";
    if (preg_match($pFields, $sDuration, $aMatch)) {
      //Add Up Hours, Minutes, and Seconds
      return $aMatch[1]*3600 + $aMatch[2]*60 + $aMatch[3];
    }
  }

  header("Content-Type: text/plain");
  $oData = getVideoDetails($sVideoId);
  print_r($oData);
  echo "Length: ".getVideoDuration($sVideoId);
?>

Hope this helps!

Motel answered 4/9, 2017 at 22:25 Comment(0)
C
0

An answer without using any Google API:

If you want the video length of a limited number of videos for a project, and you do not care about reliability (i.e., not to use in production), here is a simple and dirty Python-based web scraping solution that will not need any API key.

import requests
def get_youtube_video_length_from_url(url: str = None):
    """
    Returns youtube video length in the format minute(s): seconds from the url
    """
    text = requests.get(url).text
    str_id = text.find("""<meta itemprop="duration""")
    return (
        text[str_id : str_id + 60]
        .split("content=")[1]
        .split(">")[0]
        .replace('"', "")
        .replace("PT", "")
        .replace("M", ":")
        .replace("S", "")
    )

Example:

get_youtube_video_length_from_url("https://www.youtube.com/watch?v=dQw4w9WgXcQ")

# 3:33

I get about one result per second with that solution, and I did not get a very fast IP ban (I could query more than 200 times without any ban).

Ps: It might work as long as youtube does not change the youtube web page's code. If so, you might need to modify the code.

Cawley answered 3/3, 2023 at 17:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.