您的当前位置:首页>全部文章>文章详情

php通过IP地址获取地区

发表于:2023-05-10 11:35:33浏览:171次TAG: #PHP

前言

本文将详细介绍如何使用php通过IP地址获取地区,并提供整理的源码和通过示例代码进行说明。

php代码

/**
 * 通过IP地址获取地区
 * @param $ip
 * @return mixed|string
 */
function getRegionByIp($ip)
{
    $region = "";
    // 示例:if(window.IPCallBack){IPCallBack({"ip":"111.22.33.44","pro":"湖南省","proCode":"430000","city":"湘潭市","cityCode":"430300","region":"","regionCode":"0","addr":"湖南省湘潭市移通","regionNames":"","err":""});}
    $str = @file_get_contents("https://whois.pconline.com.cn/ipJson.jsp?ip={$ip}");
    $response = mb_convert_encoding($str,'UTF-8',array(
        'UTF-8',
        'ASCII',
        'EUC-CN',
        'CP936',
        'BIG-5',
        'GB2312',
        'GBK'
    ));
    $pattern ="/\"addr\":\"(.*?)\"/is";
    $nums = preg_match_all($pattern,$response,$result,PREG_SET_ORDER);
    $nums && $region = $result[0][1];
    return $region; // 输出=>string(25) "福建省泉州市 电信"
}