PHP将ip地址转换为实际地址

2018-01-31 10:33:51 PHP 阅读 (2648) 评论(0)
/**
 * ip转成省市区
 * @param string $ip 传入的ip
 * @return 返回一个包含省市区的数组
 */
function ipToCity($ip = ''){
    if(empty($ip)){
        return '请输入IP地址';
    }
    $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
    if(empty($res)){ return false; }
    $jsonMatches = array();
    preg_match('#\{.+?\}#', $res, $jsonMatches);
    if(!isset($jsonMatches[0])){ return false; }
    $json = json_decode($jsonMatches[0], true);
    if(isset($json['ret']) && $json['ret'] == 1){
        $json['ip'] = $ip;
        unset($json['ret']);
    }else{
        return false;
    }
    return $json;
}


评论