API Store的json使用及PHP中遍历json

作者mazerain 文章分类 分类:前端 文章评论 0条评论 阅读次数 已被围观 1100

最近看到百度的API Store,没想到提供了这么多的开放查询接口,想到以前找个用IP反查地址的简单接口找半天,不是不稳定就是不方便,终于度娘也做点好事了。

开始做的时候想着直接$getJson直接获取,没想到不能跨域请求,又想着用JsonP吧,API Store没有Callback。想了想,只好用php获取过来了。

直接用fopen,获取一点问题都没有。不过解析时候因为对php不太熟,费了半天时间,把遇到的问题整理一下。

首先要用 json_decode 对 JSON 格式的字符串进行编码

json地址:http://apistore.baidu.com/microservice/weather?citypinyin=beijing

$obj = json_decode($json);

print_r($obj);

输出:stdClass Object ( [errNum] => 0 [errMsg] => success [retData] => stdClass Object ( [city] => 北京 [pinyin] => beijing [citycode] => 101010100 [date] => 15-04-26 [time] => 11:00 [postCode] => 100000 [longitude] => 116.391 [latitude] => 39.904 [altitude] => 33 [weather] => 晴 [temp] => 32 [l_tmp] => 17 [h_tmp] => 32 [WD] => 南风 [WS] => 3-4级(10~17m/h) [sunrise] => 05:21 [sunset] => 19:03 ) )

没有问题。然后就获取相关值吧。


echo $obj['errNum'];


输出错误:Fatal error: Cannot use object of type stdClass as array in xxxxxxxx;

查了一下,stdClass得用Obj->值,这种方式。

改为echo $obj->{'errNum'};

成功输出,想要输出City就得

$arr=$obj->{'retData'};

echo $arr->{'weather'};

总结:

在PHP代码中处理JSON 格式的字符串的两种方法:

方法一:

$json= '{"errNum":0,"errMsg":"success","retData":{"city":"\u5317\u4eac","pinyin":"beijing","citycode":"101010100","date":"15-04-26","time":"11:00","postCode":"100000","longitude":116.391,"latitude":39.904,"altitude":"33","weather":"\u6674","temp":"32","l_tmp":"17","h_tmp":"32","WD":"\u5357\u98ce","WS":"3-4\u7ea7(10~17m\/h)","sunrise":"05:21","sunset":"19:03"}}';

$obj= json_decode($json);//得到的是 object

echo "返回代码:".$obj->errNum."   返回提示:".$obj->errMsg;

$arr=$obj->{'retData'};

echo "返回天气:".$arr->{'weather'};

方法二:

$json= '{"errNum":0,"errMsg":"success","retData":{"city":"\u5317\u4eac","pinyin":"beijing","citycode":"101010100","date":"15-04-26","time":"11:00","postCode":"100000","longitude":116.391,"latitude":39.904,"altitude":"33","weather":"\u6674","temp":"32","l_tmp":"17","h_tmp":"32","WD":"\u5357\u98ce","WS":"3-4\u7ea7(10~17m\/h)","sunrise":"05:21","sunset":"19:03"}}';

$dejson= json_decode($json, true);//得到的是 array

echo "返回代码:".$dejson[errNum]."   返回提示:".$dejson[errMsg]."返回天气:".$dejson[retData][weather];

如果用循环输出数据:

第一种对象用:

foreach($arr as $obj){

echo "姓名:".$obj->name."   年 龄:".$obj->age."   专 业:".$obj->subject."<br />";

}

第二种数组用:

for($i=0;$i<count($dejson);$i++){

echo "姓名:".$students[$i]['name']."   年 龄:".$students[$i]['age']."   专 业:".$students[$i]['subject']."<br />";

}
分类:前端
标签: php APIStore json

版权所有:《晋城生活服务》 => 《API Store的json使用及PHP中遍历json
本文地址:http://blog.0356sh.com/php-json.html
除非注明,文章均为 《晋城生活服务》 原创,欢迎转载!转载请注明本文地址,谢谢。

et_highlighter

发表评论: