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

  • 相关阅读:
    均值回归理论,均值回归法则是指万物最终都将回归于其长期的均值
    文本框仅允许输入大于0的正整数
    Angularjs接收服务端的布尔值
    Ajax POST单个对象或多个对象至API
    ASP.NET MVC程序重构
    查询数据库创建时间
    查询MS SQL的版本号
    获取Data和Log默认路径
    快速查找对象
    表关联使用INNER JOIN实现更新功能
  • 原文地址:https://www.cnblogs.com/behindman/p/9494311.html
Copyright © 2011-2022 走看看