有21人阅读过
简单使用php处理json内容的模板
发布于2024/05/16 更新于2024/05/16
[ 教程仅保证更新时有效,请自行测试。]
发布于2024/05/16 更新于2024/05/16
[ 教程仅保证更新时有效,请自行测试。]
[ 教程仅保证更新时有效,请自行测试。]
如果使用api获取到的内容是json格式的,需要提取指定字段的结果,可考虑一下模板:
<?php header("Content-type: text/json; charset=utf-8"); header("Cache-Control:no-cache,must-revalidate"); header("Pragma: no-cache"); function get_ip_info($ip) { $key = "xxxxx"; $url = "https://apis.map.qq.com/ws/location/v1/ip?ip=$ip&key=$key"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 5); $response = curl_exec($ch); curl_close($ch); $data = json_decode($response, true); if ($data['status'] == 'fail') { return ["error" => "无法获取IP信息"]; }; $result = [ "region" => $data['result']['ad_info']['province'], "city" => $data['result']['ad_info']['city'], "district" => $data['result']['ad_info']['district'], "ip" => $data['result']['ip'], ]; return $result; } $ip = $_GET['ip']; $url = get_ip_info($ip) ; $json= $url; echo json_encode($json, JSON_UNESCAPED_UNICODE); ?>
以上代码中,先获取到的api返回的结果如下:
{ "status": 0, "message": "Success", "request_id": "b695d2d475f347d29062eb2153ba8f4f", "result": { "ip": "2408:8459:3c40:607a:db1:500c:e2d8:ecf3", "location": { "lat": 22.55329, "lng": 113.88308 }, "ad_info": { "nation": "中国", "province": "广东省", "city": "深圳市", "district": "宝安区", "adcode": 440306, "nation_code": 156 } } }
通过
$result = [ "region" => $data['result']['ad_info']['province'], "city" => $data['result']['ad_info']['city'], "district" => $data['result']['ad_info']['district'], "ip" => $data['result']['ip'], ];
获取指定位置的结果:
$data['result']
数据在多级目录下面,就逐层用[' ']包裹起来,
"district" => $data['result']['ad_info']['district']
此时已经将json对应字段的结果赋值给指定字段了,
$region = "广东省"; $city = "深圳市"; $district = "宝安区"; $ip = "2408:8459:3c40:607a:db1:500c:e2d8:ecf3";
以上代码返回的结果是:
{ "region": "广东省", "city": "深圳市", "district": "南山区", "ip": "240e:3ba:30e0:a830:c5ba:4578:10f:b6dd" }
文章对你有帮助吗?
- 一般[0]
- 很赞[0]
- 没用[0]
- 垃圾[0]
- 无语[0]