Thursday, 11 August 2016

How to Convert Youtube Data API V3 video duration format to seconds in PHP?

How to Convert Youtube Data API V3 video duration format to seconds in PHP?

We get the youTube Video duration in below way from Youtube V3 API.
 "contentDetails": {
    "duration": "PT15S",
    "dimension": "2d",
    "definition": "sd",
    "caption": "false",
    "licensedContent": true,
    "projection": "rectangular"
   },

Now, We need to convert the duration to number of seconds.
Following are Simple PHP Function which convert the API V3 video duration format to number of seconds.
 function duration($ytDuration) {
    $di = new DateInterval($ytDuration);
    
    $totalSec = 0;
    if ($di->h > 0) {
      $totalSec+=$di->h*3600;
    }
    if ($di->i > 0) {
      $totalSec+=$di->i*60;
    }
    $totalSec+=$di->s;
    
    return $totalSec;
  }
$youtubeTime = 'PT15S';
 echo duration($youtubeTime);//15
 
 
$youtubeTime = 'PT2M55S'; 
echo duration($youtubeTime);//175

$youtubeTime = 'PT1H35M23S'; 
echo duration($youtubeTime);//5723