Maison  >  Article  >  développement back-end  >  使用新浪IP库获取IP详细地址

使用新浪IP库获取IP详细地址

WBOY
WBOYoriginal
2016-07-23 08:54:471145parcourir
使用新浪IP库获取IP详细地址
  1. class Tool{
  2. /**
  3. * 获取IP的归属地( 新浪IP库 )
  4. *
  5. * @param $ip String IP地址:112.65.102.16
  6. * @return Array
  7. */
  8. static public function getIpCity($ip)
  9. {
  10. $ip = preg_replace("/\s/","",preg_replace("/\r\n/","",$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方式获取信息
  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. * 将unicode编码转化为中文,转化失败返回原字符串
  38. *
  39. * @param $code String unicode编码
  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] => 上海 )
复制代码


Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Article précédent:百度翻译 接口使用实例 Article suivant:PHP passthru()函数使用