2017-01-11 52 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

希望這會有所幫助。

相關問題