我有以下代码,我试图从中获取jSON内容;
$url = "http://useragentapi.com/api/v3/json/APIKEY/$ua";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My Platform: ". $json_data["data.platform_name"];
我需要进入数据然后到platform_name我需要访问JSON object
的所有元素,但我可以让代码工作。
JSON结果[$json_data
]就是这样。
{
"data": {
"platform_name": "Mac OSX El Capitan",
"platform_version": "Mac OS X 10_11",
"platform_type": "Desktop",
"browser_name": "Chrome",
"browser_version": "52.0.2718.0",
"engine_name": "WebKit",
"engine_version": "537.36"
}
}
答案 0 :(得分:3)
试试这个:
$json = '{
"data": {
"platform_name": "Mac OSX El Capitan",
"platform_version": "Mac OS X 10_11",
"platform_type": "Desktop",
"browser_name": "Chrome",
"browser_version": "52.0.2718.0",
"engine_name": "WebKit",
"engine_version": "537.36"
}
}';
使用json_decode
函数解码json,并将第二个参数用作true,以便将关联数组作为输出。
$arr = json_decode($json, true);
<强>结果强>
Array
(
[data] => Array
(
[platform_name] => Mac OSX El Capitan
[platform_version] => Mac OS X 10_11
[platform_type] => Desktop
[browser_name] => Chrome
[browser_version] => 52.0.2718.0
[engine_name] => WebKit
[engine_version] => 537.36
)
)
echo $arr['data']['platform_name'];
<强>输出:强>
Mac OSX El Capitan
如果你不使用true作为
json_decode
的第二个参数,那么你必须这样做 这样:
$arr = json_decode($json);
echo $arr->data->platform_name; //Mac OSX El Capitan
答案 1 :(得分:1)
试试这个
$json = '{
"data": {
"platform_name": "Mac OSX El Capitan",
"platform_version": "Mac OS X 10_11",
"platform_type": "Desktop",
"browser_name": "Chrome",
"browser_version": "52.0.2718.0",
"engine_name": "WebKit",
"engine_version": "537.36"
}
}';
$arr = json_decode($json);
echo $arr->data->platform_name;