• 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

  • 相关阅读:
    JAVA课程作业01
    《大道至简》第二章读后感
    《大道至简》第一章读后感
    制作Linux镜像,将腾讯云服务器系统制成镜像
    postman数据驱动
    Navicat Premium 连接Oracle数据库报错 instant Client LIght : unsupported server charcter ser ZHS16GBK
    查看python位数
    AutoItLibrary安装过程中遇到的坑
    hyrobot使用
    有这样一道智力题:“某商店规定:三个空汽水瓶
  • 原文地址:https://www.cnblogs.com/cmderq/p/9130874.html
Copyright © 2020-2023  润新知