2017-01-11 51 views
0

自从2016年3月以来,我一直在使用下面的代码来获取视频持续时间($ vid_dur),直到它今天没有任何问题地使用YouTube API v3,没有任何干预侧。有什么建议么?在YouTube API v3中获取视频持续时间不起作用

<?php 
    $vidkey = "xxxxxxxxx" ; 
    $apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ; 

    $dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey"); 
    $VidDuration =json_decode($dur, true); 
    foreach ($VidDuration['items'] as $vidTime) 
    { 
    $VidDuration= $vidTime['contentDetails']['duration']; 
    } 
    // convert duration from ISO to M:S 
    $date = new DateTime('2000-01-01'); 
    $date->add(new DateInterval($VidDuration)); 

    $vid_durH= $date->format('H') ; 
     if ($vid_durH=="00") { 
      $vid_dur= $date->format('i:s') ; 
     } 
     else { 
      $vid_dur= $date->format('H:i:s') ; 
     } 
?> 

以下是错误消息

Fatal error: Uncaught exception 'Exception' with message 'DateInterval::__construct() [dateinterval.--construct]: Unknown or bad format()'

+0

回显VidDuration以查看DateInterval引发什么错误。 – johnh10

+0

{“error”:{“errors”:[{“domain”:“usageLimits”,“reason”:“keyInvalid”,“message”:“Bad Request”}],“code”:400, “Bad Request”}} –

+0

那么错误消息说,keyInvalid所以看看。 – johnh10

回答

2

我测试你的代码的一部分,这是工作。我认为您遇到file_get_contents问题,您可能需要使用Google APIs Client Library for PHP,因为它提供了对许多Google API的简单,灵活,强大的访问。

使用您的要求: 我在哪里设置$videokey=UqyT8IEBkvY(24K魔术)

"https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey" 

响应:

"items": [ 
    { 
    "kind": "youtube#video", 
    "etag": "\"GM4ZnRh2gk1X1BLWgHklTm-3cgQ/tokAeZifZMO865fU_ytDkWOyIQ0\"", 
    "id": "UqyT8IEBkvY", 
    "contentDetails": { 
    "duration": "PT3M47S", 
    "dimension": "2d", 
    "definition": "hd", 
    "caption": "false", 
    "licensedContent": true, 
    "projection": "rectangular" 
    } 
    } 
] 

您的代码:

$VidDuration= "PT3M47S"; 
$date = new DateTime('2000-01-01'); 
$date->add(new DateInterval($VidDuration)); 

$vid_durH= $date->format('H') ; 

if ($vid_durH=="00") { 
      $vid_dur= $date->format('i:s') ; 
     } 
     else { 
      $vid_dur= $date->format('H:i:s') ; 
     } 

echo $vid_dur; 

enter image description here

希望这会有所帮助。

相关问题