PHP基于新浪IP库获取IP详细地址的方法

yipeiwu_com5年前PHP代码库

本文实例讲述了PHP基于新浪IP库获取IP详细地址的方法。分享给大家供大家参考,具体如下:

<?php
class Tool{
  /**
   * 获取IP的归属地( 新浪IP库 )
   *
   * @param $ip String    IP地址:112.65.102.16
   * @return Array
   */
  static public function getIpCity($ip)
  {
    $ip = preg_replace("/\s/","",preg_replace("/\r\n/","",$ip));
    $link = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=".$ip."&t=".time();
    $ipJson = self::httpCurl($link);
    preg_match("/\"country\":\"(.*)\"/Uis",$ipJson, $match1);
    preg_match("/\"province\":\"(.*)\"/Uis",$ipJson, $match2);
    preg_match("/\"city\":\"(.*)\"/Uis",$ipJson, $match3);
    return array(
      'country'=>self::ucode2zh($match1[1]), // 国家
      'province'=>self::ucode2zh($match2[1]), // 省
      'city'=>self::ucode2zh($match3[1])   // 城市
    );
  }
  /**
   * Curl方式获取信息
   */
  static public function httpCurl($url)
  {
    $curl_handle = curl_init();
    curl_setopt($curl_handle, CURLOPT_URL, $url);
    curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT,2);
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($curl_handle, CURLOPT_FAILONERROR,1);
    $file_content = curl_exec($curl_handle);
    curl_close($curl_handle);
    return $file_content;
  }
  /**
   * 将unicode编码转化为中文,转化失败返回原字符串
   *
   * @param $code String   unicode编码
   * @return String
   */
  static public function ucode2zh($code)
  {
    $temp = explode('\u',$code);
    $rslt = array();
    array_shift($temp);
    foreach($temp as $k => $v)
    {
      $v = hexdec($v);
      $rslt[] = '&#' . $v . ';';
    }
    $r = implode('',$rslt);
    return empty($r) ? $code : $r;
  }
}

获取IP地址类使用实例

<?php
$ipStr = Tool::getIpCity('112.65.102.16');
print_r($ipStr);

返回结果

Array ( [country] => 中国 [province] => 上海 [city] => 上海 )

PS:这里再为大家提供几款IP地址相关在线工具供大家参考使用:

IP地址归属地在线查询工具:
http://tools.jb51.net/aideddesign/ipcha

在线网络计算器|TCP/IP子网掩码计算与换算工具:
http://tools.jb51.net/aideddesign/ipcalc

在线IP地址/子网掩码计算与转换工具:
http://tools.jb51.net/aideddesign/ip_net_calc

在线子网掩码换算与网络计算工具:
http://tools.jb51.net/aideddesign/network_calc

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP网络编程技巧总结》、《PHP运算与运算符用法总结》、《php文件操作总结》、《PHP基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

晋城吧对DiscuzX进行的前端优化要点

最近,康盛的DX版本基本确定,至少短期内不会大变了,因此,我对晋城吧的整站进行了前端优化,把自己 所做的操作记录下来,一是有个记录,防止忘掉,二是和网上的朋友们共享下自己的心得。 前端...

PHP简单检测网址是否能够正常打开的方法

PHP简单检测网址是否能够正常打开的方法

本文实例讲述了PHP简单检测网址是否能够正常打开的方法。分享给大家供大家参考,具体如下: 这是一个检测网址是否能正常打开的PHP代码,通过下面的代码检测一个网址是否能正常访问,如果正常则...

php的优点总结 php有哪些优点

php有哪些优点? PHP优点: 1.入门快,有其它语言基础的程序员二周左右的时间就可以入门,一个月左右的时间基本上就可以开发简单的项目了。 2.开发成本低,PHP最经典的组合就是:Li...

PHP简单计算两个时间差的方法示例

本文实例讲述了PHP简单计算两个时间差的方法。分享给大家供大家参考,具体如下: <?php //PHP计算两个时间差的方法 $startdate="2010-12-1...

PHP中simplexml_load_string函数使用说明

先用一段代码重现一下问题 乍一看,结果很让人费解: 复制代码 代码如下: <?php $string = <<<EOF <data> <foo&...