You are here

regions_api.module in Country codes API 6

Regions API provides an API for accessing country region (province/state) data.

File

contrib/regions_api/regions_api.module
View source
<?php

/**
 * @file
 * Regions API provides an API for accessing country region (province/state)
 * data.
 */

/**
 * Implementation of hook_help().
 */
function regions_api_help($path, $arg) {
  switch ($path) {
    case 'admin/help#regions_api':
      return '<p>' . t('Help Section Coming Soon.') . '</p>';
  }
}

/**
 * Function to get a region by iso2 country name
 *
 * @param $iso2
 *   A string corresponding to a regions ISO2 name.
 * @return array|null
 *   Returns an array of regions or NULL if no results found
 */
function regions_api_iso2_get_array($iso2) {
  $result = db_query("SELECT rid, iso2, name, abbreviation FROM {regions_api_regions} WHERE iso2 = '%s'", $iso2);
  $regions = array();
  while ($row = db_fetch_array($result)) {
    $regions[] = $row;
  }
  if (count($regions) == 0) {
    return NULL;
  }
  return $regions;
}

/**
 * Funtion to get an options array of country regions
 *
 * @param $iso2
 *   A string corresponding to a regions ISO2 name.
 */
function regions_api_iso2_get_options_array($iso2) {
  $result = db_query("SELECT name, abbreviation FROM {regions_api_regions} WHERE iso2 = '%s'", $iso2);
  $regions = array();
  while ($row = db_fetch_array($result)) {
    $key = drupal_strlen($row['abbreviation']) > 0 ? $row['abbreviation'] : $row['name'];
    $value = $row['name'];
    $regions[$key] = $value;
  }
  if (count($regions) == 0) {
    return NULL;
  }
  return $regions;
}

/**
 * Function to import regions from CSV file
 * TODO: provide arguments for specifying csv files
 * TODO: Setup permissions
 *
 * @param $offset
 *   Int value for csv row offset.
 */
function regions_api_csv_import_regions($offset = 1) {

  //Prepopulate regions table
  $handle = fopen(dirname(__FILE__) . "/data/regions.csv", "r");
  $index = 1;
  while (($row = fgetcsv($handle, 1024, ",")) !== FALSE) {

    //Create row variables
    $iso2 = isset($row[0]) ? $row[0] : "";
    $name = isset($row[1]) ? $row[1] : "";
    $abbreviation = isset($row[2]) ? $row[2] : "";
    if ($index > $offset) {
      db_query("INSERT INTO {regions_api_regions} (iso2, name, abbreviation) VALUES('%s', '%s', '%s')", $iso2, $name, $abbreviation);
    }
    $index++;
  }
  fclose($handle);
  watchdog('regions_api', "Pre-populated regions data.");
}

Functions

Namesort descending Description
regions_api_csv_import_regions Function to import regions from CSV file TODO: provide arguments for specifying csv files TODO: Setup permissions
regions_api_help Implementation of hook_help().
regions_api_iso2_get_array Function to get a region by iso2 country name
regions_api_iso2_get_options_array Funtion to get an options array of country regions