十年網站開發(fā)經驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網站問題一站解決
利用php怎么根據IP地址獲取所在的省市?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。

根據現有IP地址獲取其地理位置(省份,城市等)的方法
function GetIpLookup($ip = ''){
if(empty($ip)){
return '請輸入IP地址';
}
$res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
if(empty($res)){ return false; }
$jsonMatches = array();
preg_match('#\{.+?\}#', $res, $jsonMatches);
if(!isset($jsonMatches[0])){ return false; }
$json = json_decode($jsonMatches[0], true);
if(isset($json['ret']) && $json['ret'] == 1){
$json['ip'] = $ip;
unset($json['ret']);
}else{
return false;
}
return $json;
}
$ipInfos = GetIpLookup('123.125.114.144'); //baidu.com IP地址
var_dump($ipInfos);再發(fā)一個簡化版的
function getIpAddress(){
$ipContent = file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js");
$jsonData = explode("=",$ipContent);
$jsonAddress = substr($jsonData[1], 0, -1);
return $jsonAddress;
}
$ip_info=json_decode(getIpAddress());PHP根據IP地址實現城市切換或跳轉
到這里,其實問題已經很簡單了,用簡單的js就通通搞定。C段如下:
//根據IP地址跳轉指定頁面js取得城市
var city=''; //根據IP地址所有城市跳轉到指定頁面
if(city.indexOf("上海市")>=0){
window.location.; }
將開頭的A段代碼和上面的C段代碼分別放在B段代碼的頭和尾,然后我們在需要跳轉的頁面加入以下代碼:
刷新頁面,是不是達到預想的效果了呢?
看完上述內容,你們掌握利用php怎么根據IP地址獲取所在的省市的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注創(chuàng)新互聯行業(yè)資訊頻道,感謝各位的閱讀!