Home  >  Article  >  php教程  >  PHP通过其他网站获取IP地域信息实现信息的地区性

PHP通过其他网站获取IP地域信息实现信息的地区性

WBOY
WBOYOriginal
2016-06-06 19:55:491088browse

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 最近项目要求地域分布信息显示,就对IP及省市信息进行了下了解. 使用了如下2个方案来实现,用户周边信息的获取实现 1.使用了IP库,纯真IP库,可是数据库更新比较慢,文件庞大,相对所需要的资源占用较多. 2

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入

   最近项目要求地域分布信息显示,就对IP及省市信息进行了下了解.

   使用了如下2个方案来实现,用户周边信息的获取实现

   1.使用了IP库,纯真IP库,可是数据库更新比较慢,文件庞大,相对所需要的资源占用较多.

   2.调用open.baidu.com的IPSEARCH服务,使用了IP138的数据库,来获取IP所在省市信息,然后在搜索本地数据库(ecshop的region表)得到相对应的regionid ,通过ID关联相关数据

   今天测试了下感觉比较不错贴出实现代码.

   /**
   * 获取IP所在城市的信息
   * TODO:需要构造IP地址缓存
   * @param string $ip
   */
   function get_city($ip=null) {
   import('ORG.Util.Utility');
   $array = array();
   $d = M('region');
   //TODO:这里可以构造缓存以提高加载速度,这里搜索 市 列表 $cities = $d->where('`regiontype`=2')->select(); $ip = ($ip) ? $ip : get_client_ip();
   $url = "http://open.baidu.com/ipsearch/s?wd={$ip}&tn=baiduip";
   $res = mb_convert_encoding(Utility::HttpRequest($url), 'UTF-8', 'GBK');
   if ( preg_match('#来自:(.+)#Ui', $res, $m) ) {
   foreach( $cities AS $value) {
   if ( FALSE !== strpos($m[1], $value['regionname']) ) {
   //返回所在城市的IP信息
   $array['c']=$value;
   $array['p']=$d->where('`regionid`='.$value['parentid'])->find();
   return $array;
   }
   }
   }
   return array();
   }
   调用返回的结果如下array
   'c' =>
   array
   'regionid' => string '386' (length=3)
   'parentid' => string '31' (length=2)
   'regionname' => string '金华' (length=6)
   'regiontype' => string '2' (length=1)
   'agencyid' => string '0' (length=1)
   'ename' => string 'jinhua' (length=6)
   'p' =>
   array
   'regionid' => string '31' (length=2)
   'parentid' => string '1' (length=1)
   'regionname' => string '浙江' (length=6)
   'regiontype' => string '1' (length=1)
   'agencyid' => string '0' (length=1)
   'ename' => string 'zhejiang' (length=8)

   用了IP测试了下,信息还是比较准确的,IP138的IP数据库和123CHA的数据库都是国内时间库里面相对比较全面的一个.通过这种方式,性能上还可以。

PHP通过其他网站获取IP地域信息实现信息的地区性

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