IP转换成地址,一般的做法是载入DAT文件,然后再输出。
但是一般DAT文件较大,更新繁琐。现在的做法基本都是通过API接口获取。
常用的API接口有一下几种:
1、百度IP地址库接口:接口地址(http://lbsyun.baidu.com/index.php?title=webapi/ip-api),有省(自治区或直辖市)、市(县)、街道、门址、经纬度信息。返回数据如下:
{ address: "CN|北京|北京|None|CHINANET|1|None", #地址 content: #详细内容 { address: "北京市", #简要地址 address_detail: #详细地址信息 { city: "北京市", #城市 city_code: 131, #百度城市代码 district: "", #区县 province: "北京市", #省份 street: "", #街道 street_number: "" #门址 }, point: #当前城市中心点 { x: "116.39564504", y: "39.92998578" } }, status: 0 #返回状态码 }
其中status的值的含义为,0:成功,1:失败。
2、淘宝IP地址库接口:接口地址(http://ip.taobao.com/instructions.php),有国家 、省(自治区或直辖市)、市(县)、运营商信息。返回数据如下:
{ "code":0, "data":{ "ip":"210.75.225.254", "country":"\u4e2d\u56fd", "area":"\u534e\u5317", "region":"\u5317\u4eac\u5e02", "city":"\u5317\u4eac\u5e02", "county":"","isp":"\u7535\u4fe1", "country_id":"86", "area_id":"100000", "region_id":"110000", "city_id":"110000", "county_id":"-1", "isp_id":"100017" } }
其中code的值的含义为,0:成功,1:失败。
3、腾讯IP地址库接口:接口地址(http://lbs.qq.com/webservice_v1/guide-ip.html),有国家 、省(自治区或直辖市)、市(县)、经纬度信息。返回数据如下:
{ "status": 0, "message": "query ok", "result": { "location": { "lng": 116.407526, "lat": 39.90403 }, "ad_info": { "nation": "中国", "province": "", "city": "", "adcode": 110000 } } }其中code的值的含义为,0:成功,310:请求参数信息有误,311:key格式错误,306:请求有护持信息请检查字符串,110:请求来源未被授权。
4、还有其他如新浪IP、ipip.net、聚合数据等等,大家可以自己去看看。
本文主要讲下使用第一个百度IP接口的使用。
一、在TP的公共类Common.class.php中建立函数,如下:
function get_ip_curl($ip){ $url = "http://api.map.baidu.com/location/ip?ip=".$ip."&ak=***&coor=bd09ll"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); $output = curl_exec($ch); curl_close($ch); $address = json_decode($output, JSON_FORCE_OBJECT); if($address['status'] == 0){ $ip_add = $address['content']['address']; }else{ $ip_add = '暂无地址'; } return $ip_add; }上述代码中的ip代表你要查询的IP信息,ak是百度的密钥,coor的值bd09ll表示使用百度的经纬度坐标。
二、在需要的位置中载入Common.class.php文件然后就可以使用此函数了。
1、如在IndexAction.class.php中这样使用:
ip = $ip; $this->display(); } }2、在模板文件中使用:
IP IP:{$ip},IP地址:{$ip|get_ip_curl}
以上基本就可以实现IP地址的获取了。如有问题可以联系我。大家互相探讨下。
大家要问我为什么选百度的,因为貌似我用百度的速度最快......