检查IP国家/地区并显示完整的国家名称

问题描述 投票:1回答:2

我使用以下代码检查用户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'];

?>
ip country country-codes
2个回答
2
投票

看起来你正在使用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'];

?>

0
投票

我想你可以使用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'];
?>
© www.soinside.com 2019 - 2024. All rights reserved.