Home  >  Article  >  Backend Development  >  Use Sina IP library to obtain IP detailed address

Use Sina IP library to obtain IP detailed address

WBOY
WBOYOriginal
2016-07-23 08:54:471178browse
使用新浪IP库获取IP详细地址
  1. class Tool{
  2. /**
  3. * Get the IP ownership (Sina IP library)
  4. *
  5. * @param $ip String IP address: 112.65.102.16
  6. * @return Array
  7. */
  8. static public function getIpCity($ip)
  9. {
  10. $ip = preg_replace("/s/","",preg_replace("/rn/","",$ip));
  11. $link = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=".$ip."&t=".time();
  12. $ipJson = self::httpCurl($link);
  13. preg_match("/"country":"(.*)"/Uis",$ipJson, $match1);
  14. preg_match("/"province":"(.*)"/Uis",$ipJson, $match2);
  15. preg_match("/"city":"(.*)"/Uis",$ipJson, $match3);
  16. return array(
  17. 'country'=>self::ucode2zh($match1[1]), // 国家
  18. 'province'=>self::ucode2zh($match2[1]), // 省
  19. 'city'=>self::ucode2zh($match3[1]) // 城市
  20. );
  21. }
  22. /**
  23. *Curl method to obtain information
  24. */
  25. static public function httpCurl($url)
  26. {
  27. $curl_handle = curl_init();
  28. curl_setopt($curl_handle, CURLOPT_URL, $url);
  29. curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT,2);
  30. curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,1);
  31. curl_setopt($curl_handle, CURLOPT_FAILONERROR,1);
  32. $file_content = curl_exec($curl_handle);
  33. curl_close($curl_handle);
  34. return $file_content;
  35. }
  36. /**
  37. * Convert unicode encoding to Chinese, return the original string if the conversion fails
  38. *
  39. * @param $code String unicode encoding
  40. * @return String
  41. */
  42. static public function ucode2zh($code)
  43. {
  44. $temp = explode('u',$code);
  45. $rslt = array();
  46. array_shift($temp);
  47. foreach($temp as $k => $v)
  48. {
  49. $v = hexdec($v);
  50. $rslt[] = '' . $v . ';';
  51. }
  52. $r = implode('',$rslt);
  53. return empty($r) ? $code : $r;
  54. }
  55. }
复制代码
获取IP地址类使用实例
  1. $ipStr = Tool::getIpCity('112.65.102.16');
  2. print_r($ipStr);
  3. # 返回结果
  4. Array ( [country] => 中国 [province] => 上海 [city] => 上海 )
复制代码


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn