本篇文章给大家分享的内容是PHP开发小技巧之根据ip地址获取城市 ,有着一定的参考价值,有需要的朋友可以参考一下
这个方法我们用的还是比较多的,便于收集信息用于数据挖掘分析。此方法不光根据ip地址进行获取当前城市还可以根据http请求获取用户的城市位置。
实现方法:主要是根据高德地图API进行获取,首先注册成为高德地图用户,然后认证成为开发者,创建应用获取key进行调用即可。具体实现方法如下:
'json', 'key' => '4a218d0d82c3a74acf019b701e8c0ccc', 'ip' => $cip ); $postdata = http_build_query($data); $opts = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents($url, false, $context); if (!empty($result)) { $res = json_decode($result, true); if (!empty($res)) { if (count($res['province']) == 0) { $res['province'] = '北京市'; } if (!empty($res['province']) && $res['province'] == "局域网") { $res['province'] = '北京市'; } if (count($res['city']) == 0) { $res['city'] = '北京市'; } } else { $res['province'] = '北京市'; $res['city'] = '北京市'; } return $res; } else { return array( "province" => '北京市', "city" => '北京市' ); } }
相关推荐:











