如何从PHP中的以下json获取“duration”值:
{
"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": ""
}
}
}
]
}
尝试了很多例子,但是它会导致对象错误或索引错误无效吗?
答案 0 :(得分: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'];
}
答案 1 :(得分: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'];
}
答案 2 :(得分:1)
试试这个
这里的网址视频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;
?>