php获取ip归属地

  • 黄楚恒
  • 2019-09-03 10:55:12
  • PHP
  • php
<?php
//太平洋网络查询ip,较快
     $ip = "14.117.179.49";
     $get_ip_city = get_ip_city($ip);
     var_dump($get_ip_city);
 
 
     /**
      *$ip  string  必传
      *获取ip归属地 
      *demo 广东省江门市 电信 
      */
     function get_ip_city($ip){     	
	     $ch = curl_init();
	     $url = 'https://whois.pconline.com.cn/ipJson.jsp?ip='.$ip;
	     //用curl发送接收数据
	     curl_setopt($ch, CURLOPT_URL, $url);
	     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	     //请求为https
	     curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
	     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	     $location = curl_exec($ch);
	     curl_close($ch);
	     //转码
	     $location = mb_convert_encoding($location, 'utf-8','GB2312');
	     //var_dump($location);
	     //截取{}中的字符串
	     $location = substr($location, strlen('({')+strpos($location, '({'),(strlen($location) - strpos($location, '})'))*(-1));
	    //将截取的字符串$location中的‘,’替换成‘&’   将字符串中的‘:‘替换成‘=’
	     $location = str_replace('"',"",str_replace(":","=",str_replace(",","&",$location)));
	     //php内置函数,将处理成类似于url参数的格式的字符串  转换成数组
	     parse_str($location,$ip_location);
	     return $ip_location['addr'];
}



//淘宝接口较慢
function get_ip_city($ip)
{
    $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
    $ipinfo=json_decode(file_get_contents($url));
    if($ipinfo->code=='1'){
        return false;
    }
    $location = $ipinfo->data->region.$ipinfo->data->city.$ipinfo->data->isp;
    return $location;
}

Copyright © 2016-2019 709173702@qq.com 版权所有  ICP证粤ICP备16117826号-1
联系邮箱:709173702@qq.com