我无法使用 json_decode 将此JSON响应解码为PHP,感谢您的帮助:
来自API的JSON响应
{
"fixtures": [
{
"id": 59757,
"home_team_id": 24,
"away_team_id": 18,
"home_score_penalties": 0,
"away_score_penalties": 0,
"formation": {
"home": null,
"away": null
},
"date_time_tba": false,
"spectators": null,
"round_id": 4839
}
]
}
PHP:
$url = "https://api....";
$data = json_decode(file_get_contents($url), true);
echo $data['fixtures'][0]['home_team_id'];
echo $data['formation'][0]['home'];
我没有结果!
谢谢。答案 0 :(得分:3)
那里有JSON验证器的镜像。在使用json_decode
之前使用其中任何一个。
{
"fixtures": [{
"id": 59757,
"home_team_id": 24,
"away_team_id": 18,
"home_score_penalties": 0,
"away_score_penalties": 0,
"formation": {
"home": null,
"away": null
},
"date_time_tba": false,
"spectators": null,
"round_id": 4839,
}]
}
您的示例无法使用有效的JSON,因为"round_id": 4839,
最终不能使用逗号。有效的JSON将是:
{
"fixtures": [{
"id": 59757,
"home_team_id": 24,
"away_team_id": 18,
"home_score_penalties": 0,
"away_score_penalties": 0,
"formation": {
"home": null,
"away": null
},
"date_time_tba": false,
"spectators": null,
"round_id": 4839
}]
}
现在这个JSON在解码后返回一个数组:
$json = '{"fixtures": [{"id": 59757,"home_team_id": 24,"away_team_id": 18,"home_score_penalties": 0,"away_score_penalties": 0,"formation": {"home": null,"away": null},"date_time_tba": false,"spectators": null,"round_id": 4839}]}';
var_dump(json_decode($json, true));
结果:
array(1) {
["fixtures"]=>
array(1) {
[0]=>
array(9) {
["id"]=>
int(59757)
["home_team_id"]=>
int(24)
["away_team_id"]=>
int(18)
["home_score_penalties"]=>
int(0)
["away_score_penalties"]=>
int(0)
["formation"]=>
array(2) {
["home"]=>
NULL
["away"]=>
NULL
}
["date_time_tba"]=>
bool(false)
["spectators"]=>
NULL
["round_id"]=>
int(4839)
}
}
}
答案 1 :(得分:2)
首先检查您是否正在接收var_dump(file_get_contents($url))
的输出。
然后验证返回的字符串是否为有效的JSON。由Nordenheim解释here
一旦确认其有效,请检查JSON解码数据以了解如何访问正确的值。
var_dump(json_decode(file_get_contents($url)));
所以以下内容应该是你要找的;
$data = json_decode(file_get_contents($url));
echo $data['data'][0]['id'];
;