PHP获取IP地址、手机号码归属地方法类库


亲测可用

header("Content-type:text/html;charset=utf-8");
if(version_compare(PHP_VERSION,'5.4.0','<')){
	die('PHP版本要求不低于5.4');
}

$helper = new TaoBaoLocation();

/*
//返回数组
$arr = $helper->iplocation('223.145.33.234',true);
var_dump($arr);
*/

//返回字符串
echo $helper->iplocation('223.145.33.234');

//echo $helper->tellocation('18221228700');


class TaoBaoLocation{
	
	public $errorInfo = ''; //获取失败的返回值
	//获取IP归属地
	public function iplocation($ip,$needArr=false){
		$html = $this->curl_get("http://ip.taobao.com/service/getIpInfo.php?ip=".$ip);
		$js = json_decode($html,true);
		if(empty($js) || !isset($js['code']) || intval($js['code'])!==0){
			return $this->errorInfo;
		}
		if($needArr){
			return $js["data"];
		}
		return $js["data"]["region"].$js["data"]["city"]."&nbsp;&nbsp;".$js["data"]["isp"];
	}
	//获取手机号归属地
	public function tellocation($tel){
		$html = $this->curl_get("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel={$tel}");
		if(empty($html) || strpos($html,"carrier:")+11 > strpos($html,"}")){
			return $this->errorInfo;
		}
		$html  = iconv("gb2312","utf-8",$html);
		$html = substr($html,strpos($html,"carrier")+9);
		$html = substr($html,0,strpos($html,"'"));
		return $html;	
	}
	private function curl_get($geturl){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$geturl);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_TIMEOUT,30);
		if(strpos($geturl,"https") !== false){
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		}
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}
}