zoukankan      html  css  js  c++  java
  • php获取ip地址所在的地理位置的实现

    1,通过腾讯或者新浪提供的接口来获取(新浪和腾讯类似)

    <?php 
       function getIPLocation($queryIP){ 
        $url = 'http://ip.qq.com/cgi-bin/searchip?searchip1='.$queryIP; 

      //如果是新浪,这里的URL是:'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$queryIP; 
        $ch = curl_init($url); 
        curl_setopt($ch,CURLOPT_ENCODING ,'gb2312'); 
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回 
        $result = curl_exec($ch); 
        $result = mb_convert_encoding($result, "utf-8", "gb2312"); // 编码转换,否则乱码 
     //   print_r($result);
        curl_close($ch); 
        preg_match("@<span>(.*)</span></p>@iU",$result,$ipArray); //匹配标签,抓取查询到的ip地址(以数组的形式返回)
        $location = $ipArray[0]; 
        return $location; 



    $ip = getIPLocation('111.186.116.208');//将ip传入进来
    print_r($ip);//打印结果
    ?>

    如果把提交的$result打印出来的话,显示如下:

    最后显示的结果为中国上海市  教育

    2,通过淘宝提供的接口

    <?php
    header("Content-type:text/html;charset=utf-8");//设置编码格式
    function getCity($ip)
    {
       $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
       print_r(file_get_contents($url));
       $ipinfo=json_decode(file_get_contents($url)); 
       if($ipinfo->code=='1'){
           return false;
       }
       $city = $ipinfo->data->region.$ipinfo->data->city;
       return $city; 
    }
     
    // example
    print_r(getCity("111.186.116.208"));
    ?>

    打印出-打开的url地址后,可以发现,它是以json格式返回数据的,因此需要进行解码(json_decode)

    最后得到的结果为:上海市上海市

    参考文章:

    PHP淘宝IP数据获取用户IP及地理位置                     http://www.111cn.net/phper/php/48159.htm

    使用PHP+淘宝IP地址库接口获得IP所属地理位置  http://www.ttlsa.com/php/to-obtain-ip-location-using-the-php-taobao-ip-address-database-interface/

    PHP获取IP地址所在的地理位置                                 http://jingyan.baidu.com/article/154b46315e74af28ca8f4137.html

  • 相关阅读:
    Redis 如何设置密码及验证密码?
    怎么测试 Redis 的连通性?
    Redis 的内存用完了会发生什么?
    假如 Redis 里面有 1 亿个 key,其中有 10w 个 key 是以 某个固定的已知的前缀开头的,如果将它们全部找出来?
    使用过 Redis 做异步队列么,你是怎么用的?
    简述在 MySQL 数据库中 MyISAM 和 InnoDB 的区别 ?
    你怎么看到为表格定义的所有索引?
    深入理解卷积网络的卷积
    OpenCV-Python 图像阈值 | 十五
    OpenCV-Python 图像的几何变换 | 十四
  • 原文地址:https://www.cnblogs.com/behindman/p/9494311.html
Copyright © 2011-2022 走看看