简体   繁体   中英

Mapping country code to country name php

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

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];
}

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

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.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM