Alaa Sadik
Alaa Sadik

Reputation: 1089

Getting video duration does not work in YouTube API v3

I have been using the code below to get the video duration ($vid_dur) using YouTube API v3 since March 2016 and without any problem until it stooped working today without any intervention from my side. Any suggestions?

<?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') ;  
        } 
?>

Here is part of the error message

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

Upvotes: 1

Views: 674

Answers (1)

Mr.Rebot
Mr.Rebot

Reputation: 6791

I've tested your code, it is working. I think you are encountering problems with file_get_contents, you might want to use the Google APIs Client Library for PHP as it offers simple, flexible, powerful access to many Google APIs.

Using you request : Where I set $videokey=UqyT8IEBkvY (24K Magic)

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

Response:

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

Your code :

$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

Hope this helps.

Upvotes: 3

Related Questions