function countries_import_csv in Countries 8
Same name and namespace in other branches
- 7.2 countries.install \countries_import_csv()
- 7 countries.install \countries_import_csv()
Helper function to import countries.
1 call to countries_import_csv()
- countries_install in ./
countries.install - Implements hook_install().
File
- ./
countries.install, line 126 - Install file for Countries module.
Code
function countries_import_csv() {
$t = get_t();
$langcode = language_default('language');
$countries = array();
$handle = fopen(dirname(__FILE__) . '/countries.csv', 'r');
$headers = fgetcsv($handle, 1024, ",");
while (($row = fgetcsv($handle, 1024, ",")) !== FALSE) {
// The iso2 data.
$row[0] = trim($row[0]);
// The iso3 data.
$row[1] = empty($row[1]) || $row[1] == 'NULL' ? '' : trim($row[1]);
// The name data.
$row[2] = empty($row[2]) || $row[2] == 'NULL' ? '' : $t(trim($row[2]), array(), array(
'langcode' => $langcode,
));
// The official name data.
$row[3] = empty($row[3]) || $row[3] == 'NULL' ? '' : $t(trim($row[3]), array(), array(
'langcode' => $langcode,
));
// The number code data.
$row[4] = empty($row[4]) || $row[4] == 'NULL' ? 0 : trim($row[4]);
// The continent data.
$row[5] = empty($row[5]) || $row[5] == 'NULL' ? 'UN' : trim($row[5]);
// The enabled data.
$row[6] = empty($row[6]) || $row[6] == 'NULL' ? 0 : 1;
if (!empty($row[0]) && $row[0] != 'NULL') {
$countries[$row[0]] = array(
'iso2' => $row[0],
'iso3' => $row[1],
'name' => $row[2],
'official_name' => $row[3],
'numcode' => $row[4],
'continent' => $row[5],
'enabled' => $row[6],
);
}
}
fclose($handle);
include_once DRUPAL_ROOT . '/includes/iso.inc';
foreach (_country_get_predefined_list() as $code => $name) {
if (array_key_exists($code, $countries)) {
$countries[$code]['enabled'] = 1;
}
else {
drupal_set_message($t('Missing details for ISO 3166-1 alpha-2 code %code for %name in Countries data.', array(
'%code' => $code,
'%name' => $name,
)), 'warning');
$countries[$code] = array(
'iso2' => $code,
'iso3' => '',
'name' => $name,
'official_name' => '',
'continent' => 'UN',
'enabled' => 1,
'numcode' => 0,
);
}
}
$insert = db_insert('countries_country')
->fields(array(
'iso2',
'iso3',
'name',
'official_name',
'continent',
'enabled',
'numcode',
));
foreach ($countries as $country) {
$insert
->values($country);
}
$insert
->execute();
watchdog('countries', "Pre-populated countries data.");
}