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

Posted

技术标签:

【中文标题】php没有从freegeoip.net获取邮政编码【英文标题】:php not grabbing zip code from freegeoip.net 【发布时间】:2018-10-06 14:19:24 【问题描述】:

到目前为止,我的脚本可以提取 ip、lat 和 long。邮政编码没有被删除。我无法弄清楚什么是坏的以及它需要什么才能使它工作。有什么想法吗?

// 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 API将于今年7月1日全面停产:github.com/apilayer/freegeoip#readme 一般提示:非常小心 php 的“闭嘴”运算符 @。您可能会抑制重要的输出,尤其是在开发过程中。 谢谢@Chris .. 我删除了那些,但不记得在那里看到它们。 【参考方案1】:

旧的 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;

【讨论】:

@Zack Abrams 我已经用新的 API 添加了这个新代码,但我无法让它工作。 // Initialize CURL: $ch = curl_init('https://api.ipstack.com/'.$ipaddress.'?access_key='.$access_key.''); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Store the data: $json = curl_exec($ch); curl_close($ch); // Decode JSON response: $api_result = json_decode($json, true); // Output the "capital" object inside "location" $lat = $api_result['location']['latitude']; $lon = $api_result['location']['longitude']; $zip = $api_result['location']['zip']; lat 、 lon 和 zip 变量不在位置索引中。试试这个: $url = '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['纬度']; $lon = $api_result['经度']; $zip = $api_result['zip'];回声 $zip; 我更改了设置 $lat = $api_result['latitude']; $lon = $api_result['longitude']; $zip = $api_result['zip']; 的位置,但它仍然没有回显或返回变量。 我的第一个答案中的 curl 选项不会返回要保存为变量的数据。使用评论中的 curl 调用(我也会更新答案以反映这一点)

以上是关于php没有从freegeoip.net获取邮政编码的主要内容,如果未能解决你的问题,请参考以下文章

有没有像freegeoip.net这样的网站[关闭]

FreeGeoIP.net Webservice - 服务值得信赖吗?

PHP - 打印 GeoIP 数组

将 XML 数据提取到 php [重复]

如何从 MVC 中的 ip 地址获取格式化地址

公网IP查看网址