时间:2021-07-01 10:21:17 帮助过:32人阅读
你的代码就这些?那把json里面注释去掉。。。
你的代码就这些?那把json里面注释去掉。。。
$obj->basic->id
json_decode($json, true);
出来的就是数组了
好像不行,这样没法提取单个数据值
当我从一个URL获取了json包之后,$res = curl_exec($ch); 不论怎么处理,整个json包都会展现出来,而不是我想要提取的其中某个字段
$ch = curl_init();
$url = 'https://api.heweather.com/x3/weather?cityid=CN101200101&key=7081f8010abe4638a86e0c4c1cfee30e';
// 执行HTTP请求
curl_setopt($ch , CURLOPT_URL , $url);
curl_setopt($ch , CURLOPT_SSL_VERIFYPEER , false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = json_decode(curl_exec($ch));
echo $res['now']['cond']['txt'];
?>
这段请求无法获取到需要的天气值
echo $res[key($res)][0]['now']['cond']['txt']; //多云
其实你 print_r($res); 就可以看到 now 是在第三维的
注释去掉即可
$res = '{ "status": "ok", "basic": { "city": "北京", "cnty": "中国", "id": "CN101010100", "lat": "39.904000", "lon": "116.391000", "update": { "loc": "2015-07-02 14:44", "utc": "2015-07-02 06:46" } }}';var_dump(json_decode($res)); //显示结果
$res = '{ "status": "ok", "basic": { "city": "北京", "cnty": "中国", "id": "CN101010100", "lat": "39.904000", "lon": "116.391000", "update": { "loc": "2015-07-02 14:44", "utc": "2015-07-02 06:46" } }}';$data = json_decode($res); //显示结果echo $data->basic->id;
echo $res[key($res)][0]['now']['cond']['txt']; //多云
其实你 print_r($res); 就可以看到 now 是在第三维的
注释去掉即可
$res = '{ "status": "ok", "basic": { "city": "北京", "cnty": "中国", "id": "CN101010100", "lat": "39.904000", "lon": "116.391000", "update": { "loc": "2015-07-02 14:44", "utc": "2015-07-02 06:46" } }}';var_dump(json_decode($res)); //显示结果
$res = '{ "status": "ok", "basic": { "city": "北京", "cnty": "中国", "id": "CN101010100", "lat": "39.904000", "lon": "116.391000", "update": { "loc": "2015-07-02 14:44", "utc": "2015-07-02 06:46" } }}';$data = json_decode($res); //显示结果echo $data->basic->id;
$ch = curl_init();$url = 'https://api.heweather.com/x3/weather?cityid=CN101200101&key=7081f8010abe4638a86e0c4c1cfee30e';// 执行HTTP请求curl_setopt($ch , CURLOPT_URL , $url);curl_setopt($ch , CURLOPT_SSL_VERIFYPEER , false);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);$res = json_decode(curl_exec($ch), true); //json_decode 要有第二个参数,这样可解析成数组echo $res[key($res)][0]['now']['cond']['txt'], PHP_EOL; //为什么要这样写,看看 print_r 的输出就知道了print_r($res);