php根据ip地址获取地理位置

目前我测试过的有三种方法可以根据ip地址获取地理位置,第一种是通过新浪IP查询接口获取,第二种是通过腾讯IP查询接口获取,第三种是通过ip138查询。

一、新浪IP查询接口地址:http://int.dpool.sina.com.cn/iplookup/iplookup.php

后面带有两个参数:ip=你要查询的ip地址,format=返回的查询结果格式,现在使用json

	function getAddressFromIp_sina($ip) {
		$url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=".$ip;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$addr = curl_exec($ch);
		$data = json_decode($addr);
		curl_close($ch);

		if($data->ret == "1") {
			$result = $data->province.",".$data->city.",".$data->isp;
		} else {
			$result = "未能定位成功";
		}

		return $result;
	}



二、腾讯IP查询接口地址:http://ip.qq.com/cgi-bin/searchip

后面带有一个参数:searchip1=你要查询的ip地址

	function getAddressFromIp_tencent($ip) {
		$url = "http://ip.qq.com/cgi-bin/searchip?searchip1=".$ip;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_ENCODING, 'GB2312');
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$data = curl_exec($ch);
		$data = mb_convert_encoding($data, "UTF-8", "GB2312");
		curl_close($ch);
		print_r($data);
	}


这种方式刚开始是成功的,后来一直返回空,原因还在寻找...


三、IP138 IP查询接口地址:http://www.ip138.com/ips138.asp

后面带有一个参数:ip=你要查询的ip地址

	function getAddressFromIp_ips($ip) {
		$url = "http://www.ip138.com/ips138.asp?ip=".$ip;
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_ENCODING, "GB2312");
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$data = curl_exec($ch);
		$data = mb_convert_encoding($data, "UTF-8", "GB2312");
		curl_close($ch);
		preg_match("/本站主数据:.*<\/li>
  • /", $data, $result); print_r($result); }





  • 你可能感兴趣的:(PHP快速入门,php,ip,地理位置)