PHP 如何读取如下的JSON数据?

2025-04-22 20:48:17
推荐回答(2个)
回答1:

php内置json编码和解析函数

$response=file_get_contents('https://apis.map.qq.com/ws/location/v1/ip?ip=120.239.177.236&key=申请的QQ地图密钥');

//把字符串解析为数组,第二个参数默认false,解析为对象
$json = json_decode($response,true);

echo $json['location']['lng'];
echo $json['location']['lat'];

//把数组编码成字符串输出,第二个参数为不编码unicode字符(汉字就属于unicode,不编码则原样显示,编码后为 \uxxxx 的格式)
echo json_encode($json,JSON_UNESCAPED_UNICODE);

回答2:

$tmp = '{"status":0,"message":"query ok","result":{"elements":[{"from":{"lat":37.05983,"lng":114.46816},"to":{"lat":37.069569,"lng":114.493048},"distance":3369,"duration":536}]}}';
$arr = json_decode($tmp,true);
print_r($arr["result"]["elements"][0]["distance"]);