Convert youtube Api v3 video duration in php

2019-01-19 10:30发布

how do i convert PT2H34M25S to 2:34:25

I searched and used this code. I'm new to regex can someone explain this ? and help me with my issue

function covtime($youtube_time){
        preg_match_all('/(\d+)/',$youtube_time,$parts);
        $hours = floor($parts[0][0]/60);
        $minutes = $parts[0][0]%60;
        $seconds = $parts[0][1];
        if($hours != 0)
            return $hours.':'.$minutes.':'.$seconds;
        else
            return $minutes.':'.$seconds;
    }   

but this code only give me HH:MM

so dumb found the solution :

   function covtime($youtube_time){
            preg_match_all('/(\d+)/',$youtube_time,$parts);
            $hours = $parts[0][0];
            $minutes = $parts[0][1];
            $seconds = $parts[0][2];
            if($seconds != 0)
                return $hours.':'.$minutes.':'.$seconds;
            else
                return $hours.':'.$minutes;
        }

12条回答
淡お忘
2楼-- · 2019-01-19 11:01

try this will give you duration by seconds

function video_length($youtube_time)
{
    $duration = new \DateInterval($youtube_time);
    return $duration->h  * 3600 + $duration->i  * 60  + $duration->s;
}
查看更多
聊天终结者
3楼-- · 2019-01-19 11:03

Using DateTime class

You could use PHP's DateTime class to achieve this. This solution is much simpler, and will work even if the format of the quantities in the string are in different order. A regex solution will (most likely) break in such cases.

In PHP, PT2H34M25S is a valid date period string, and is understood by the DateTime parser. We then make use of this fact, and just add it to the Unix epoch using add() method. Then you can format the resulting date to obtain the required results:

function covtime($youtube_time){
    $start = new DateTime('@0'); // Unix epoch
    $start->add(new DateInterval($youtube_time));
    return $start->format('H:i:s');
}   

echo covtime('PT2H34M25S');

Demo

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-19 11:06

This is my solution, test completed!

preg_match_all("/PT(\d+H)?(\d+M)?(\d+S)?/", $duration, $matches);

$hours   = strlen($matches[1][0]) == 0 ? 0 : substr($matches[1][0], 0, strlen($matches[1][0]) - 1);
$minutes = strlen($matches[2][0]) == 0 ? 0 : substr($matches[2][0], 0, strlen($matches[2][0]) - 1);
$seconds = strlen($matches[3][0]) == 0 ? 0 : substr($matches[3][0], 0, strlen($matches[3][0]) - 1);

return 3600 * $hours + 60 * $minutes + $seconds;
查看更多
再贱就再见
5楼-- · 2019-01-19 11:09

I use two classes, 1 to call YouTube API, and one to convert the time. here it is simplified.

As you can see, YouTubeGet is a static class, but it does not have to be. YouTubeDateInterval however has to be an instance due to the way that DateInterval works (which is being extended).

class YouTubeGet{
static public function get_duration($video_id, $api_key){
        // $youtube_api_key
        $url = "https://www.googleapis.com/youtube/v3/videos?id={$video_id}&part=contentDetails&key={$api_key}";
        // Get and convert. This example uses wordpress wp_remote_get()
        // this could be replaced by file_get_contents($url);
        $response = wp_remote_get($url);

        // if using file_get_contents(), then remove ['body']
        $result = json_decode($response['body'], true);
        // I've converted to an array, but this works fine as an object
        if(isset($result['items'][0]['contentDetails']['duration'])){
            $duration = $result['items'][0]['contentDetails']['duration'];
            return self::convtime($duration);
        }
        return false;
    }

    static protected function convtime($youtube_time){
        $time = new YouTubeDateInterval($youtube_time);        
        return $time->to_seconds();
    }   

}

class YouTubeDateInterval extends DateInterval {
    public function to_seconds() 
      { 
        return ($this->y * 365 * 24 * 60 * 60) + 
               ($this->m * 30 * 24 * 60 * 60) + 
               ($this->d * 24 * 60 * 60) + 
               ($this->h * 60 * 60) + 
               ($this->i * 60) + 
               $this->s; 
      } 
}

usage is either about passing a iso 8601 date to YouTubeDateInterval.

$time = new YouTubeDateInterval('PT2H34M25S');
$duration_in_seconds = $time->to_seconds();

or passing the YouTubeGet the api and video id key

$duration_in_seconds = YouTubeGet::get_duration('videoIdString','YouTubeApiKeyString');
查看更多
冷血范
6楼-- · 2019-01-19 11:09

Try the following function:

function covtime($youtube_time) 
{
    $hours = '0';
    $minutes = '0';
    $seconds = '0';

    $hIndex = strpos($youtube_time, 'H');
    $mIndex = strpos($youtube_time, 'M');
    $sIndex = strpos($youtube_time, 'S');
    $length = strlen($youtube_time);
    if($hIndex > 0)
    {
        $hours = substr($youtube_time, 2, ($hIndex - 2));
    }
    if($mIndex > 0)
    {
        if($hIndex > 0)
        {
            $minutes = substr($youtube_time, ($hIndex + 1), ($mIndex - ($hIndex + 1)));
        }      
        else
        {
            $minutes = substr($youtube_time, 2, ($mIndex - 2));
        }
    }
    if($sIndex > 0)
    {
        if($mIndex > 0)
        {
            $seconds = substr($youtube_time, ($mIndex + 1), ($sIndex - ($mIndex + 1)));
        }
        else if($hIndex > 0)
        {
            $seconds = substr($youtube_time, ($hIndex + 1), ($sIndex - ($hIndex + 1)));
        }      
        else
        {
            $seconds = substr($youtube_time, 2, ($sIndex - 2));
        }
    }
    return $hours.":".$minutes.":".$seconds;        
}
查看更多
霸刀☆藐视天下
7楼-- · 2019-01-19 11:10

Here's my solution which handles missing H, M or S (test a video with a reported length of 1:00:01 and you'll see the problem with other answers). Seconds alone are presented as 0:01, but if you want to change that just change the last else to elseif($M>0) and add an else for seconds e.g. else { return ":$S" }

// convert youtube v3 api duration e.g. PT1M3S to HH:MM:SS
// updated to handle videos days long e.g. P1DT1M3S
function covtime($yt){
    $yt=str_replace(['P','T'],'',$yt);
    foreach(['D','H','M','S'] as $a){
        $pos=strpos($yt,$a);
        if($pos!==false) ${$a}=substr($yt,0,$pos); else { ${$a}=0; continue; }
        $yt=substr($yt,$pos+1);
    }
    if($D>0){
        $M=str_pad($M,2,'0',STR_PAD_LEFT);
        $S=str_pad($S,2,'0',STR_PAD_LEFT);
        return ($H+(24*$D)).":$M:$S"; // add days to hours
    } elseif($H>0){
        $M=str_pad($M,2,'0',STR_PAD_LEFT);
        $S=str_pad($S,2,'0',STR_PAD_LEFT);
        return "$H:$M:$S";
    } else {
        $S=str_pad($S,2,'0',STR_PAD_LEFT);
        return "$M:$S";
    }
}
查看更多
登录 后发表回答