【问题标题】:Check IP country and display full country name检查 IP 国家并显示完整的国家名称
【发布时间】:2016-06-03 06:54:49
【问题描述】:

我使用以下代码检查用户 IP 的位置。 但这会显示像“US”和“UK”这样的国家/地区。

如何解决这个问题以显示完整的国家名称? 比如“美国”和“英国”?

CODE:

<?php

$ipaddress = $_SERVER['REMOTE_ADDR'];

function ip_details($ip) {
  $json = file_get_contents("http://ipinfo.io/{$ip}/json");
  $details = json_decode($json, true);
  return $details;
}

$details = ip_details($ipaddress);
echo $details['country'];

?>

【问题讨论】:

  • 你的问题是什么?你的代码有错误吗?
  • @weigreen 不,它工作正常!我只想将显示的国家代码编辑为国家名称。国家现在显示为“美国”,我想显示为“美国”
  • 嗨 Henk,您可以改用 ipdata.co,我们提供完整的国家名称、货币、货币符号和调用代码以及直接来自 API 的所有其他数据点,无需额外工作。

标签: ip country country-codes


【解决方案1】:

看起来您正在使用 ipinfo 的 API。

他们只为您提供简短的国家/地区名称。

不过,ipinfo's document 表示您可以使用“country.io”的数据来满足您的需求。

只要转换成php数组,就可以转美国到美国了

<?php

$ipaddress = $_SERVER['REMOTE_ADDR'];

$code = ["US" => "United States", "GB" => "United Kingdom"];

function ip_details($ip) {
    $json = file_get_contents("http://ipinfo.io/{$ip}/json");
    $details = json_decode($json, true);
    return $details;
}

$details = ip_details($ipaddress);
if(array_key_exists($details['country'], $code)){
    $details['country'] = $code[$details['country']];
}
echo $details['country'];

?>

【讨论】:

  • 谢谢!唯一的问题是,在这种情况下,国家将被转换为英文国家名称。我想把它翻译成我们自己的语言。有没有办法说,如果价值是“美国”显示“美国”?
  • 更新我的答案,您可以更改$code 中的数据,其中key 作为国家代码,value 作为您语言的国家名称。
【解决方案2】:

我认为您可以使用 checkgeoip.com。它是免费的:

<?php
// set IP address and API key 
$ip = '72.229.28.185';
$api_key = 'YOUR_API_KEY';

// Initialize CURL:
$ch = curl_init('https://api.checkgeoip.com/'.$ip.'?api_key='.$api_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 "city" object
echo $api_result['city'];
?>

【讨论】:

    猜你喜欢
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    相关资源
    最近更新 更多