0

How to get the "duration" value from the below json in PHP :

{
 "kind": "youtube#videoListResponse",
 "etag": "\"6jI4SSPcXxEAc3i_1EQHOPi0Cvc/EGNSBh81ISlkeECbqD9xdh5C340\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#video",
   "etag": "\"6jI4SSPcXxEAc3i_1EQHOPi0Cvc/yUebIRJfQ62Pq5XpRbqJHx7Xozo\"",
   "id": "7lCDEYXw3mM",
   "contentDetails": {
    "duration": "PT15M51S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "true",
    "licensedContent": false,
    "contentRating": {
     "ytRating": ""
    }
   }
  }
 ]
}

Tried many examples but either it results in object error or invalid index error ?

Stacked
  • 841
  • 2
  • 12
  • 23

3 Answers3

2
$jsonObj  = json_decode($json);
$duration = $jsonObj->items[0]->contentDetails->duration;

or

$jsonArr  = json_decode($json, true);
$duration = $jsonArr['items'][0]['contentDetails']['duration'];

or in a loop:

$jsonArr  = json_decode($json, true);
foreach ($jsonArr['items'] as $item) {
    echo $item['contentDetails']['duration'];
}
Daniel W.
  • 31,164
  • 13
  • 93
  • 151
  • Tested the first one and it works, thanks :). Any ideas how to convert the parsed "ISO 8601" duration into seconds ? – Stacked Sep 20 '13 at 05:29
  • 1
    have a look into this question :-) http://stackoverflow.com/questions/3721085/parse-and-create-iso-8601-date-and-time-intervals-like-pt15m-in-php – Daniel W. Sep 20 '13 at 07:56
  • 2
    Thanks, this did the trick : ```$interval = new DateInterval($duration); $tseconds = (($interval->format('%h')*60)*60)+($interval->format('%i')*60)+$interval->format('%s'); echo $tseconds;``` – Stacked Sep 20 '13 at 08:40
1
$json = <<<JSON
{
 "kind": "youtube#videoListResponse",
 "etag": "\"6jI4SSPcXxEAc3i_1EQHOPi0Cvc/EGNSBh81ISlkeECbqD9xdh5C340\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#video",
   "etag": "\"6jI4SSPcXxEAc3i_1EQHOPi0Cvc/yUebIRJfQ62Pq5XpRbqJHx7Xozo\"",
   "id": "7lCDEYXw3mM",
   "contentDetails": {
    "duration": "PT15M51S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "true",
    "licensedContent": false,
    "contentRating": {
     "ytRating": ""
    }
   }
  }
 ]
}
JSON;

$data = json_decode($json);

foreach ($data['items'] as $item) {
    echo $item['contentDetails']['duration'];
}
Joran Den Houting
  • 3,149
  • 3
  • 21
  • 51
1

Try this

here in url video id is id of video please remember to change it

<?php
$url=file_get_contents("https://gdata.youtube.com/feeds/api/videos/videoid?v=2");
$data = json_decode($url);

$duration = $data['items']['duration'];
echo $duration;
?>
Janak Prajapati
  • 896
  • 1
  • 9
  • 36