Create a PHP array containing the code of the ISO 3166-2 country subdivisions

It’s not easy to find a ISO 3166-2 country region code file. After some Google searches, I ended up on a Debian page with the ISO codes.

Alternating Rice Plots in the Bacson Valley in July. (Hai Thinh Hoang, July 2012) www.boston.com/bigpicture/2013/03/smithsonian_magazine_2012_phot.html

Download iso-codes/iso_3166_2/iso_3166_2.xml

I found a PHP script about the country codes and modified it to support regions:

<?php
$filecontent = file_get_contents(‘iso_3166_2.xml’);
$xml = new SimpleXMLElement($filecontent);
$out = “<?php
$regions = array();
“;
foreach ($xml->iso_3166_country as $country)
{
foreach ($country->iso_3166_subset as $regions) {
foreach ($regions->iso_3166_2_entry as $region) {

$out .= “\$regions[‘”.$country->attributes()->code.”’] [‘”.$region->attributes()->code.”’]=’”.addslashes($region->attributes()->name).”’;”;
}
}
}
file_put_contents(‘isoregionnames.php’, $out);
Blog post from June 28, 2010