淘宝公司提供了一个很好用的IP地理信息查询接口。
在这里:http://ip.taobao.com/
TaobaoIPQuery2这个类将极大的简化相关的信息查询。
类 TaobaoIPQuery2 文件:
1 <?php 2 /* Usage: 3 * $IPInfo = TaobaoIPQuery2::getIPInfo('IPAddress'); 4 5 http://www.cnblogs.com/roucheng/ 6 */ 7 Class TaobaoIPQuery2{ 8 private static $_requestURL = 'http://ip.taobao.com/service/getIpInfo.php'; 9 public static function getIPInfo($ip){10 $long = ip2long($ip);11 if($long === 0){12 throw new Exception('IP address error', 5);13 }14 $ip=long2ip($long);15 $IPInfo = self::queryIPInfo($ip);16 return self::parseJSON($IPInfo);17 }18 19 private static function queryIPInfo($ip){20 $query = http_build_query(array('ip'=>$ip));21 $ch = curl_init();22 $options = array(23 CURLOPT_URL => sprintf('%s?%s', self::$_requestURL, $query),24 CURLOPT_RETURNTRANSFER => true,25 CURLOPT_AUTOREFERER => false,26 CURLOPT_FOLLOWLOCATION => false,27 CURLOPT_HEADER => false,28 CURLOPT_TIMEOUT => 3.0,29 );30 curl_setopt_array($ch, $options);31 $content = curl_exec($ch);32 curl_close($ch);33 return $content;34 }35 36 private static function parseJSON($json){37 $O = json_decode ($json, true);38 if(false === is_null($O)){39 return $O;40 }41 if (version_compare(PHP_VERSION, '5.3.0', '>=')) {42 $errorCode = json_last_error();43 if(isset(self::$_JSONParseError[$errorCode])){44 throw new Exception(self::$_JSONParseError[$errorCode], 5);45 }46 }47 throw new Exception('JSON parse error', 5);48 }49 50 private static $_JSONParseError = array(51 JSON_ERROR_NONE=>'No error has occurred', 52 JSON_ERROR_DEPTH=>'The maximum stack depth has been exceeded', 53 JSON_ERROR_CTRL_CHAR=>'Control character error, possibly incorrectly encoded', 54 JSON_ERROR_STATE_MISMATCH=>'Invalid or malformed JSON', 55 JSON_ERROR_SYNTAX=>'Syntax error', 56 JSON_ERROR_UTF8=>'Malformed UTF-8 characters, possibly incorrectly encoded',57 );58 }