Reputation: 438
I have a function that I found on here to get the user ip to country. but it only shows the abrev I want to show the full country as well as the abrev
function ip_details($IPaddress)
{
$json = file_get_contents("http://ipinfo.io/{$IPaddress}");
$details = json_decode($json);
return $details;
}
$IPaddress = 'get ip here';
$details = ip_details("$IPaddress");
echo $details->region;
echo $details->country;
then I echo where I want it like this.
<?php echo $details->country;?>
So I went to IpInfo Site
it tells me to download and map I have downloaded the json file but unsure how to map it so that I can echo out the full country name when needed
Upvotes: 1
Views: 4411
Reputation: 61904
This snippet gets the output I think you want from the JSON.
You can substitute the hard-coded IP address for the the value from your script once you're happy with this.
$countries = json_decode(file_get_contents('http://country.io/names.json'));
$details = json_decode(file_get_contents("http://ipinfo.io/8.8.8.8"));
$code = $details->country;
echo "Country Name: ".$countries->$code."<br/>";
echo "Country Code: ".$code."<br/>";
echo "Region: ".$details->region."<br/>";
echo "City: ".$details->city."<br/>";
This outputs:
Country Name: United States
Country Code: US
Region: California
City: Mountain View
Upvotes: 2
Reputation: 1476
I would take the country codes from the JSON and create a PHP array in your code for quick lookup.
$countryCodes = ['BD'=>'Bangladesh', ...];
if ( array_key_exists($details->country, $countryCodes) {
$country = $countryCodes[$details->country];
}
Upvotes: 2
Reputation: 2365
You can use below function to get the country name from country code:
function getCountryName($code) {
$json = file_get_contents("http://country.io/names.json");
$countries = json_decode($json, TRUE);
return array_key_exists($code,$countries) ? $countries[$code] : false;
}
As a improvement, you can download the http://country.io/names.json
json file and refer it here instead of calling it remotely every time.
Upvotes: 1
Reputation: 1646
You will need to use PHP's json_decode
function to turn the JSON data into an array.
Example:
$country_json = file_get_contents('http://country.io/names.json');
$country_array = json_decode($country_json, TRUE); // TRUE turns the result into an associative array
echo $country_array[$details->country];
Upvotes: -2