我使用以下代码来检查用户IP的位置。但这会显示像"美国"和"英国"这样的国家/地区。
如何解决此问题以显示完整的国家/地区名称?比如"美国"和"英国"?
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'];
?>
看起来您正在使用ipinfo的API。
他们只为您提供简短的国家/地区名称。
但是,ipinfo的文件说您可以使用"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'];
?>
我认为您可以使用 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'];
?>