You are here

function countries_import_csv in Countries 7

Same name and namespace in other branches
  1. 8 countries.install \countries_import_csv()
  2. 7.2 countries.install \countries_import_csv()

Helper function to import countries.

1 call to countries_import_csv()
countries_install in ./countries.install
Implement hook_install().

File

./countries.install, line 97
Install file for Countries API.

Code

function countries_import_csv() {
  $t = get_t();
  $countries = array();
  $handle = fopen(dirname(__FILE__) . "/countries.csv", "r");
  $headers = fgetcsv($handle, 1024, ",");
  while (($row = fgetcsv($handle, 1024, ",")) !== FALSE) {
    $row[0] = trim($row[0]);

    // iso2
    $row[1] = empty($row[1]) || $row[1] == 'NULL' ? '' : trim($row[1]);

    // iso3
    $row[2] = empty($row[2]) || $row[2] == 'NULL' ? '' : trim($row[2]);

    // name
    $row[3] = empty($row[3]) || $row[3] == 'NULL' ? '' : trim($row[3]);

    // official name
    $row[4] = empty($row[4]) || $row[4] == 'NULL' ? 0 : trim($row[4]);

    // number code
    $row[5] = empty($row[5]) || $row[5] == 'NULL' ? 'UN' : trim($row[5]);

    // continent
    $row[6] = empty($row[6]) || $row[6] == 'NULL' ? 0 : 1;

    // enabled
    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]['name'] = $name;
      $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' => $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.");
}