Convert country codes

James picture James · Aug 11, 2010 · Viewed 22.4k times · Source

There are several methods on country codes.

I have a list of codes with 3-characters, like on this page:

http://www.fina.org/H2O/index.php?option=com_content&view=category&id=93:asia&Itemid=638&layout=default

Is there a simple way to convert them to 2-characters? Like "PT" from "POR" for Portugal.

Standard for 2-characters - http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2

Thanks.

Answer

Ben Dowling picture Ben Dowling · Sep 10, 2014

There are some useful data files that you can get from http://country.io/data that'll help you:

If you just want to go from 3 letter codes to 2 letter codes you can just flip the first map and use that. You could create a map that goes directly from 3 letter codes to country names by combing the files though. Here's a simple PHP example:

$codes = json_decode(file_get_contents('http://country.io/iso3.json'), true);
$names = json_decode(file_get_contents('http://country.io/names.json'), true);
$iso3_to_name = array();
foreach($codes as $iso2 => $iso3) {
    $iso3_to_name[$iso3] = $names[$iso2];
}

echo $names("PL"); // => "Poland"
echo $iso3_to_map("POL"); // => "Poland"