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 ?

3
  • Show the PHP object, not the original JSON. Commented Sep 19, 2013 at 12:17
  • Once json_decoded, you can say ['items']['contentDetails']['duration'] Commented Sep 19, 2013 at 12:17
  • please post what u tried... Commented Sep 19, 2013 at 12:18

3 Answers 3

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'];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Tested the first one and it works, thanks :). Any ideas how to convert the parsed "ISO 8601" duration into seconds ?
have a look into this question :-) stackoverflow.com/questions/3721085/…
Thanks, this did the trick : $interval = new DateInterval($duration); $tseconds = (($interval->format('%h')*60)*60)+($interval->format('%i')*60)+$interval->format('%s'); echo $tseconds;
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'];
}

Comments

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;
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.