Skip to content

Instantly share code, notes, and snippets.

@treffynnon
Created February 4, 2010 15:18
Show Gist options
  • Save treffynnon/294722 to your computer and use it in GitHub Desktop.
Save treffynnon/294722 to your computer and use it in GitHub Desktop.
Get ISO list of countries
<?php
//Get ISO list of countries
$iso_xml_zip_file_url = 'http://www.iso.org/iso/';
$iso_xml_zip_filename = 'iso_3166-1_list_en.zip';
$iso_xml_zip_new_filename = 'iso_3166-1_list_en_'.date('Y-m-d').'.zip';
$iso_xml_filename = 'iso_3166-1_list_en.xml';
$download_directory = './temp/';
//setup database variables
$table_name = 'countries';
$country_column_name = 'original';
$country_column_capitalised_name = 'name';
$country_column_alpha = 'alpha';
//download the file
if(!file_exists($download_directory.$iso_xml_zip_new_filename))
copy($iso_xml_zip_file_url.$iso_xml_zip_filename, $download_directory.$iso_xml_zip_new_filename) or die('Could not copy '.$iso_xml_zip_file_url.$iso_xml_zip_filename.' to '.$download_directory.$iso_xml_zip_new_filename);
$za = new ZipArchive();
$za->open($download_directory.$iso_xml_zip_new_filename) or die('Cannot open ZIP file - possibly corrupt.');
$xml = $za->getFromName($iso_xml_filename) or die('Cannot extract XML file ('.$iso_xml_filename.') - perhaps the ZIP is corrupt.');
//clean up the names of the elements so they will work as objects
$xml = str_replace(array('ISO_3166-1_', '-2_Code_element', '_name'), '', $xml);
$xml = simplexml_load_string($xml);
$SQL = '';
foreach($xml->Entry as $entry) {
$SQL .= "INSERT INTO `$table_name` SET
`$country_column_name` = '".mysql_escape_string($entry->Country)."',
`$country_column_capitalised_name` = '".mysql_escape_string(ucwords(strtolower($entry->Country)))."',
`$country_column_alpha` = '".mysql_escape_string($entry->Alpha)."';\n\n";
}
print '<pre>'.$SQL.'</pre>';
if(!file_exists($download_directory.$iso_xml_zip_new_filename))
copy($iso_xml_zip_file_url.$iso_xml_zip_filename, $download_directory.$iso_xml_zip_new_filename) or die('Could not copy '.$iso_xml_zip_file_url.$iso_xml_zip_filename.' to '.$download_directory.$iso_xml_zip_new_filename);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment