利用的是淘宝的接口,大家看代码就应该懂了吧,就是从淘宝IP库取回一条result写到数组里,然后输出就好了。
/**
* 通过IP获取对应城市信息(该功能基于淘宝第三方IP库接口)
* @param $ip IP地址,如果不填写,则为当前客户端IP
* @return 如果成功,则返回数组信息,否则返回false
*/
function get_client_ip($type = 0) {
$type = $type ? 1 : 0;
static $ip = NULL;
if ($ip !== NULL) return $ip[$type];
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown',$arr);
if(false !== $pos) unset($arr[$pos]);
$ip = trim($arr[0]);
}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$long = sprintf("%u",ip2long($ip));
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
}
function getIpInfo($ip){
if(empty($ip)) $ip=get_client_ip();
$url='http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;
$result = file_get_contents($url);
$result = json_decode($result,true);
if($result['code']!==0 || !is_array($result['data'])) return false;
return $result['data'];
}
结果例子:
Array
(
[country] => 中国
[country_id] => CN
[area] => 华南
[area_id] => 800000
[region] => 广东省
[region_id] => 440000
[city] => 深圳市
[city_id] => 440300
[county] =>
[county_id] => -1
[isp] => 电信
[isp_id] => 100017
[ip] => 113.116.200.48
)