将 Youtube Data API V3 视频时长格式转换为 PHP 中的标准时间


Converting Youtube Data API V3 video duration format to standard time in PHP

我是从youtube API请求中获取此数组的,但在我看来,持续时间格式非常罕见。他们为什么不在那里投入几秒钟?无论如何,这是数组

[duration] => PT2M3S
[dimension] => 2d
[definition] => sd
[caption] => false

有没有办法在 PHP 中将此持续时间转换为"H:i:s"格式?

提前感谢您的帮助

acidjazz 有一个很好的解决方案,但它显示分钟的地方有一个错别字。它应该$di->i几分钟,而不是$di->m.如果您不在对象中使用它,您也可以删除"公共静态"部分,并且我取出了sprintf()

否则,该函数按原样工作:

function duration($ytDuration) {
    $di = new DateInterval($ytDuration);
    $string = '';
    if ($di->h > 0) {
      $string .= $di->h.':';
    }
    return $string.$di->i.':'.$di->s;
}

我会将此作为评论添加到他的答案中,但是整个"您需要 50 个声誉才能评论"BS 阻止我坚持这个线程的流程。

事实上,日期ISO8601很简单。使用正则表达式拆分字符串,例如('d+)分钟和秒。然后得到分钟除以 60 的整数部分得到小时数。获取该部门的剩余部分以获得分钟数。

这是一个应该可以工作的示例,尽管我没有对其进行测试

preg_match_all('/('d+)/',$youtube_time,$parts);
$hours = floor($parts[0][0]/60);
$minutes = $parts[0][0]%60;
$seconds = $parts[0][1];

你可以使用 php 的 DateInterval 类来正确解析它。例如,youtube包装类中的一个函数,用于将其解析为YouTube显示的格式:

  public static function duration($ytDuration) {
    $di = new DateInterval($ytDuration);
    $string = '';
    if ($di->h > 0) {
      $string .= $di->h.':';
    }
    return $string.$di->m.':'.sprintf('%02s',$di->s);
  }

我在这里使用了@chris-z-s的答案,并将其转换为php:

function getDurationSeconds($duration){
    preg_match_all('/[0-9]+[HMS]/',$duration,$matches);
    $duration=0;
    foreach($matches as $match){
        //echo '<br> ========= <br>';       
        //print_r($match);      
        foreach($match as $portion){        
            $unite=substr($portion,strlen($portion)-1);
            switch($unite){
                case 'H':{  
                    $duration +=    substr($portion,0,strlen($portion)-1)*60*60;            
                }break;             
                case 'M':{                  
                    $duration +=substr($portion,0,strlen($portion)-1)*60;           
                }break;             
                case 'S':{                  
                    $duration +=    substr($portion,0,strlen($portion)-1);          
                }break;
            }
        }
    //  echo '<br> duratrion : '.$duration;
    //echo '<br> ========= <br>';
    }
     return $duration;
}

它与我一起工作:)

也许有人会有所帮助:

$interval = new 'DateInterval($iso8601);
// in seconds:
$seconds = $interval->h * 360 + $interval->i * 60 + $interval->s;
// in "H:i:s" format:
echo $interval->format('%H:%i:%s');
这是我

的解决方案:

preg_match('/('d+)H/', $duration, $match);
$h = ($match[0])?filter_var($match[0], FILTER_SANITIZE_NUMBER_INT).":":'';
preg_match('/('d+)M/', $duration, $match);
$m = filter_var($match[0], FILTER_SANITIZE_NUMBER_INT).":";
preg_match('/('d+)S/', $youtube_date, $match);
$s = filter_var($match[0], FILTER_SANITIZE_NUMBER_INT);
echo: "Duration: " . $h.$m.$s;

##:##:## PHP 上的时间格式

 function NormalizeDuration($duration){
    preg_match('#PT(.*?)H(.*?)M(.*?)S#si',$duration,$out);
    if(empty($out[1])){
    preg_match('#PT(.*?)M(.*?)S#si',$duration,$out);
    if(empty($out[1])){
    preg_match('#PT(.*?)S#si',$duration,$out);
    if(empty($out[1])){
    return '00:00';
    }
    }else{
    if(strlen($out[1])==1){ $out[1]= '0'.$out[1]; }
    if(strlen($out[2])==1){ $out[2]= '0'.$out[2]; }
    return $out[1].':'.$out[2];
    }
    }else{
    if(strlen($out[1])==1){ $out[1]= '0'.$out[1]; }
    if(strlen($out[2])==1){ $out[2]= '0'.$out[2]; }
    if(strlen($out[3])==1){ $out[3]= '0'.$out[3]; }
    return $out[1].':'.$out[2].':'.$out[3];
    }
    }

使用以下php函数将返回YouTube视频时长。有关更多令人兴奋的代码,请点击此链接 更多代码示例

    function getYoutubeDuration($vid) 
    {
    $videoDetails =file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=".$vid."&part=contentDetails&key=AIzaSyDen99uTRRPl9VT_Ra9eAisvZSc4aZDEns");
    $videoDetails =json_decode($videoDetails, true);
    foreach ($videoDetails['items'] as $vidTime)
     {
        $youtube_time = $vidTime['contentDetails']['duration'];
        preg_match_all('/('d+)/',$youtube_time,$parts);
        $hours = (strlen(floor($parts[0][0]/60))<1)?floor($parts[0][0]/60):'0'.floor($parts[0][0]/60);
        $minutes = $parts[0][0]%60; (strlen($parts[0][0]%60)<1)?$parts[0][0]%60:'0'.$parts[0][0]%60;
        $seconds = $parts[0][1];(strlen($parts[0][1])<1)?$parts[0][1]:'0'.$parts[0][1];
        return $hours.":".$minutes.":".$seconds;
     }
    }
  echo getYoutubeDuration('J1lb3qJgfho');

由于YouTube(谷歌)喜欢困难,他们选择非标准格式。因此,标准函数并不总是有效。

因此,我这样做是为了我的需要。

$length = $data['items'] ..... ['duration'];
$seconds = substr(stristr($length, 'S', true), -2, 2);
$seconds = preg_replace("/[^0-9]/", '', $seconds);
$minutes =  substr(stristr($length, 'M', true), -2, 2);
$minutes = preg_replace("/[^0-9]/", '', $minutes);
$hours =  substr(stristr($length, 'H', true), -2, 2);
$hours = preg_replace("/[^0-9]/", '', $hours);

具有命名组的解决方案

PT((?P<hours>'d+)H)?((?P<minutes>'d+)M)?((?P<seconds>'d+)S)?

可以在此处找到示例 https://regex101.com/r/wU3hT2/114

蟒蛇函数:

def yt_time_to_seconds(time):
    regex_string = 'PT((?P<hours>'d+)H)?((?P<minutes>'d+)M)?((?P<seconds>'d+)S)?'
    regex = re.compile(regex_string)
    match = regex.match(time)
    if match:
        hours = int(match.group('hours'))
        minutes = int(match.group('minutes'))
        seconds = int(match.group('seconds'))
        return hours * 60 * 60 + minutes * 60 + seconds
    return 0

>它对我 100% 完美地工作,只有你应该有 '' 日期间隔作为根

function NormalizeDuration($duration){ //pass your time
    $start = new 'DateTime('@0');
    $start->add(new 'DateInterval($duration));
    return $start->format('H:i:s'); //format
}