php 没有从 freegeoip.net 获取邮政编码

php not grabbing zip code from freegeoip.net

到目前为止,我使用的脚本可以提取 ip、纬度和经度。邮政编码没有被取消。我不知道什么坏了,需要什么才能让它工作。有什么想法吗?

// Function to get the client ip address
function getUserIP()
{
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }

    return $ip;
}

$ipaddress = getUserIP();

$geoIP  = 
json_decode(file_get_contents("http://freegeoip.net/json/$ipaddress"), true);

$lat = $geoIP['latitude'];
$lon = $geoIP['longitude'];
$zip = $geoIP['zip'];

旧的 freegeoip 已经贬值,新服务 ipstack 提供免费 api 访问。下面是一个简单的 curl 调用,它将获取您想要的信息(以及更多信息)。

$url = 'http://api.ipstack.com/134.201.250.155?access_key=YOURKEY';  
$ch = curl_init();  

curl_setopt($ch, CURLOPT_URL, $url);  
curl_setopt($ch, CURLOPT_HEADER, 0);  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   

$output = curl_exec($ch);  

$api_result = json_decode($output, true); 

$lat = $api_result['latitude']; 
$lon = $api_result['longitude']; 
$zip = $api_result['zip'];

echo $zip;
echo $lat;
echo $lon;