Creating a PHP array of ISO 3166-1 Country Codes

Thursday 7th January, 2010 — 5 Comments

I recently came across which has an ISO 3166-1 list of country codes for various programming languages. I wanted to generate an HTML drop down list for customer to choose from based on these codes. However, there is no PHP version provoided. So taking the XML version found at I made a trivial script that would take the codes found in the XML document and organise them in to a PHP array called $XML2PHPCountryCodes and save that array in a file called country_names.php. The output file can then be included in any PHP script making the contained array available.

< ?php
$str = file_get_contents(
$xml = new SimpleXMLElement($str);
$out = '$countries'." = array(\n";
foreach ($xml->country as $country)
  $out .= "'{$country['code']}' => \"{$country['name']}\",\n";
$out .= ");";

file_put_contents('country_names.php', $out);



5 responses to Creating a PHP array of ISO 3166-1 Country Codes

  1. thanks useful script

  2. Thanks for this little piece of code :) I used it for the 3166-2 country subdivisions codes:

  3. The URL provided no longer functions.

  4. Would it be possible to make an upgrade and use the official resource site :

Trackbacks and Pingbacks:

  1. Create a PHP array containing the code of the ISO 3166-2 country subdivisions at Moodle, IT and me - Friday 2nd April, 2010

    [...] I just needed a little PHP script. I quickly found one about the country codes and modified it to support [...]

Leave a Reply


Text formatting is available via select HTML. <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>