Question

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.

Was it helpful?

Solution

There is going to be no easy way because there is no particular scheme in the names of the country. For example PT from POR for Portugal and this can be different for other countries as well. You might want to create an array to hold two letters for each country.

Example:

$countries = array('PT' => 'Portugal', 'UK' => 'United Kingdom');

OTHER TIPS

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"

I see that the question was asked seven years ago. Today I had the similar issue and found one good solution. Hope that this answer will be helpful to others who will have the same issue in the future.

There is a separate library which can be used https://github.com/thephpleague/iso3166

Then the solution would be straightforward. $alpha3 is the three char representation of a country. And alpha2 is two char representation of the country.

  1. $ composer require league/iso3166
  2. $data = (new League\ISO3166\ISO3166)->alpha3($alpha3);
  3. Data looks as follows:

    [
      'name' => 'Netherlands',
      'alpha2' => 'NL',
      'alpha3' => 'NLD',
      'numeric' => '528',
      'currency' => [
        'EUR',
        ]
    ]
    
  4. $countryCodeInTwoChar = $data['alpha2']

Without doing an actual lookup, there is no simple way: AFG (Afghanistan) becomes AF, while AND (Andorra) becomes AD, and BLR (Belarus) becomes BY... so you can't do any simple character manipulation to convert.

My suggestion would be to use a countrycode table, or add an extra column to any existing table, so that you hold both codes.

There is a similar question in gis.stackexchange.
https://gis.stackexchange.com/questions/603/is-a-country-state-city-database-available
I think you will get more information by posting this questions in gis. http://gis.stackexchange.com

For anyone tackling this, I've made a JSON mapping alpha3 to alpha2. Download here: https://api.myjson.com/bins/1y2hn

So you would just assign this JSON to an object (example countryCodes). Now converting is just: countryCodes["US"] //"USA"

Most of the other answers above are not direct answers. Let me try

I have tried below code to convert 3-characters to 2-characters country code using API:

<?php
    $list=["BWA","SLV","TZA","BRB","IND","BES","ANT"];
    $iso3=file_get_contents('http://country.io/iso3.json');//load the country codes
    $iso3=json_decode($iso3,true);//convert json to associative array
    foreach($list as $k)
    {
        if($k=="ANT")//not defined in code list
            echo "AN";
        else
            echo array_search($k,$iso3); 
        echo "<br/>";
    }
?>

The country codes provided is in form of 2-iso(key):3-iso(value). So instead of searching for key, i searched by value and return the first corresponding key if successful.

Output

BW

SV

TZ

BB

IN

BQ

AN

Cons -

ANT country code is not defined in code list.

Reference - array_search

While this may be a lengthy and painful method, it may very well be worth your while writing a function that you can keep forever more, maybe this can point you in the right direction:

<?php
function myCodes($in, $type){
$out = "";
$long = array('portugal', 'united kingdom');
$short = array('pt', 'uk');
$in = strtolower(trim($in));
switch($type){
case 'long':$out = str_replace($short, $long, $in);break;
case 'short':$out = str_replace($long, $short, $in);break;
}
echo $out;
}

echo myCodes('United Kingdom', 'short'); //this will echo 'uk'
echo myCodes('UK', 'long'); //this will echo 'united kingdom'

?>

This will of course have a few drawbacks such as making sure that the arrays for long and short match up position wise, and you'll need to maintain the function as well.

A Json based array with ISO 3 codes but not sorted

Paste Bin Link

And PHP Array Paste BIN PHP Array

$mapping['POR'] = 'PT';
$shortcode = $mapping[$longcode];

In ruby you can get this done like this: (get countryInfo.txt from http://download.geonames.org/export/dump/ )

require 'csv'
countries_iso3_map = {}
CSV.foreach('countryInfo.txt',:col_sep=>'   ',:row_sep =>:auto) do |row|
   next if row[0][0] == '#' #ignore comments section
   countries_iso3_map[row[0][0,2]]= row[1][0,3]
end
p countries_iso3_map['PT']

Building on the other info here, here's a complete function ready to go:

function convertCountryAlphas3To2($code='') {
 $countries = json_decode('{"AFG":"AF","ALA":"AX","ALB":"AL","DZA":"DZ","ASM":"AS","AND":"AD","AGO":"AO","AIA":"AI","ATA":"AQ","ATG":"AG","ARG":"AR","ARM":"AM","ABW":"AW","AUS":"AU","AUT":"AT","AZE":"AZ","BHS":"BS","BHR":"BH","BGD":"BD","BRB":"BB","BLR":"BY","BEL":"BE","BLZ":"BZ","BEN":"BJ","BMU":"BM","BTN":"BT","BOL":"BO","BIH":"BA","BWA":"BW","BVT":"BV","BRA":"BR","VGB":"VG","IOT":"IO","BRN":"BN","BGR":"BG","BFA":"BF","BDI":"BI","KHM":"KH","CMR":"CM","CAN":"CA","CPV":"CV","CYM":"KY","CAF":"CF","TCD":"TD","CHL":"CL","CHN":"CN","HKG":"HK","MAC":"MO","CXR":"CX","CCK":"CC","COL":"CO","COM":"KM","COG":"CG","COD":"CD","COK":"CK","CRI":"CR","CIV":"CI","HRV":"HR","CUB":"CU","CYP":"CY","CZE":"CZ","DNK":"DK","DKK":"DK","DJI":"DJ","DMA":"DM","DOM":"DO","ECU":"EC","Sal":"El","GNQ":"GQ","ERI":"ER","EST":"EE","ETH":"ET","FLK":"FK","FRO":"FO","FJI":"FJ","FIN":"FI","FRA":"FR","GUF":"GF","PYF":"PF","ATF":"TF","GAB":"GA","GMB":"GM","GEO":"GE","DEU":"DE","GHA":"GH","GIB":"GI","GRC":"GR","GRL":"GL","GRD":"GD","GLP":"GP","GUM":"GU","GTM":"GT","GGY":"GG","GIN":"GN","GNB":"GW","GUY":"GY","HTI":"HT","HMD":"HM","VAT":"VA","HND":"HN","HUN":"HU","ISL":"IS","IND":"IN","IDN":"ID","IRN":"IR","IRQ":"IQ","IRL":"IE","IMN":"IM","ISR":"IL","ITA":"IT","JAM":"JM","JPN":"JP","JEY":"JE","JOR":"JO","KAZ":"KZ","KEN":"KE","KIR":"KI","PRK":"KP","KOR":"KR","KWT":"KW","KGZ":"KG","LAO":"LA","LVA":"LV","LBN":"LB","LSO":"LS","LBR":"LR","LBY":"LY","LIE":"LI","LTU":"LT","LUX":"LU","MKD":"MK","MDG":"MG","MWI":"MW","MYS":"MY","MDV":"MV","MLI":"ML","MLT":"MT","MHL":"MH","MTQ":"MQ","MRT":"MR","MUS":"MU","MYT":"YT","MEX":"MX","FSM":"FM","MDA":"MD","MCO":"MC","MNG":"MN","MNE":"ME","MSR":"MS","MAR":"MA","MOZ":"MZ","MMR":"MM","NAM":"NA","NRU":"NR","NPL":"NP","NLD":"NL","ANT":"AN","NCL":"NC","NZL":"NZ","NIC":"NI","NER":"NE","NGA":"NG","NIU":"NU","NFK":"NF","MNP":"MP","NOR":"NO","OMN":"OM","PAK":"PK","PLW":"PW","PSE":"PS","PAN":"PA","PNG":"PG","PRY":"PY","PER":"PE","PHL":"PH","PCN":"PN","POL":"PL","PRT":"PT","PRI":"PR","QAT":"QA","REU":"RE","ROU":"RO","RUS":"RU","RWA":"RW","BLM":"BL","SHN":"SH","KNA":"KN","LCA":"LC","MAF":"MF","SPM":"PM","VCT":"VC","WSM":"WS","SMR":"SM","STP":"ST","SAU":"SA","SEN":"SN","SRB":"RS","SYC":"SC","SLE":"SL","SGP":"SG","SVK":"SK","SVN":"SI","SLB":"SB","SOM":"SO","ZAF":"ZA","SGS":"GS","SSD":"SS","ESP":"ES","LKA":"LK","SDN":"SD","SUR":"SR","SJM":"SJ","SWZ":"SZ","SWE":"SE","CHE":"CH","SYR":"SY","TWN":"TW","TJK":"TJ","TZA":"TZ","THA":"TH","TLS":"TL","TGO":"TG","TKL":"TK","TON":"TO","TTO":"TT","TUN":"TN","TUR":"TR","TKM":"TM","TCA":"TC","TUV":"TV","UGA":"UG","UKR":"UA","ARE":"AE","GBR":"GB","USA":"US","UMI":"UM","URY":"UY","UZB":"UZ","VUT":"VU","VEN":"VE","VNM":"VN","VIR":"VI","WLF":"WF","ESH":"EH","YEM":"YE","ZMB":"ZM","ZWE":"ZW","GBP":"GB","RUB":"RU","NOK":"NO"}',true);
 $out = $countries[$code];
 return $out;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top