0

如何从 PHP 中的以下 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": ""
    }
   }
  }
 ]
}

尝试了许多示例,但要么导致对象错误或无效索引错误?

4

3 回答 3

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

或者

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

或循环:

$jsonArr  = json_decode($json, true);
foreach ($jsonArr['items'] as $item) {
    echo $item['contentDetails']['duration'];
}
于 2013-09-19T12:18:43.400 回答
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'];
}
于 2013-09-19T12:20:57.097 回答
1

试试这个

这里在 url video id 是视频的 id 请记得更改它

<?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;
?>
于 2013-09-19T12:21:56.323 回答