📔 浅紫日记

Php如何获取API接口返回JSON数组所对应参数值
📅 2026-07-30 19:52 📂

PHP如何获取API接口返回JSON数组所对应参数值

采用直接访问数组元素获取JSON数组的参数值:获取JSON数组的值?输出JSON数组?如何提取JSON数组中的值?以ip接口为例:

1、访问 http://ip-api.com/json/".$ip."?lang=zh-CN  所输出的结果为:

{"status":"success","country":"中国","countryCode":"CN","region":"GD","regionName":"广东","city":"矮车","zip":"","lat":23.7385,"lon":115.8129,"timezone":"Asia/Shanghai","isp":"China Mobile communications corporation","org":"China Mobile","as":"AS9808 Guangdong Mobile Communication Co.Ltd.","query":"128.212.230.78"}

2、访问 http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=".$ip  所输出的结果为:

{"ip":"128.212.230.78","pro":"广东省","proCode":"440000","city":"梅州市","cityCode":"441400","region":"","regionCode":"0","addr":"广东省梅州市 移通","regionNames":"","err":""}

根据对比第一个api所获取的city(村名)比第二个获取的city(市名)的更为精准,但第一个没有市级名,而获取到了国家的名字等等,那干脆就两者结合加于判断筛选,我们就可以得到一个比较理想的结果。

image.png

image.png

$filenames = "http://ip-api.com/json/".$ip."?lang=zh-CN";
$contents = file_get_contents($filenames);
$contents =  json_decode($contents, true);
echo $contents['query'];//ip
echo $contents['country'];//国家
echo $contents['regionName'];//省州
echo $contents['city'];//地市
echo $contents['timezone'];//时区
echo $contents['isp'];//公司
echo $contents['org'];//组织
echo $contents['as'];//公司组织
 
$filename = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=".$ip;
$content = file_get_contents($filename);
$content = iconv("gb2312", "utf-8//IGNORE",$content); //进行编码,负责乱码
$content =  json_decode($content, true); 
echo $content['ip'];//ip
echo $content['pro'];//省份
echo $content['city'];//城市
echo $content['addr'];//地区网络//guojia
⬅ 返回列表