1,通過騰訊或者新浪提供的接口來獲取(新浪和騰訊類似)
<?php
function getIPLocation($queryIP){
$url = 'http://ip.qq.com/cgi-bin/searchip?searchip1='.$queryIP;
//如果是新浪,這里的URL是:'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$queryIP;
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_ENCODING ,'gb2312');
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 獲取數據返回
$result = curl_exec($ch);
$result = mb_convert_encoding($result, "utf-8", "gb2312"); // 編碼轉換,否則亂碼
// print_r($result);
curl_close($ch);
preg_match("@<span>(.*)</span></p>@iU",$result,$ipArray); //匹配標簽,抓取查詢到的ip地址(以數組的形式返回)
$location = $ipArray[0];
return $location;
}
$ip = getIPLocation('111.186.116.208');//將ip傳入進來
print_r($ip);//打印結果
?>
如果把提交的$result打印出來的話,顯示如下:
最后顯示的結果為中國上海市 教育
2,通過淘寶提供的接口
<?php
header("Content-type:text/html;charset=utf-8");//設置編碼格式
function getCity($ip)
{
$url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
print_r(file_get_contents($url));
$ipinfo=json_decode(file_get_contents($url));
if($ipinfo->code=='1'){
return false;
}
$city = $ipinfo->data->region.$ipinfo->data->city;
return $city;
}
// example
print_r(getCity("111.186.116.208"));
?>
打印出-打開的url地址后,可以發現,它是以json格式返回數據的,因此需要進行解碼(json_decode)
最后得到的結果為:上海市上海市
參考文章:
PHP淘寶IP數據獲取用戶IP及地理位置 http://www.111cn.net/phper/php/48159.htm
使用PHP+淘寶IP地址庫接口獲得IP所屬地理位置 http://www.ttlsa.com/php/to-obtain-ip-location-using-the-php-taobao-ip-address-database-interface/
PHP獲取IP地址所在的地理位置 http://jingyan.baidu.com/article/154b46315e74af28ca8f4137.html