Skip to content

Instantly share code, notes, and snippets.

@noginn
Created August 19, 2009 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noginn/170266 to your computer and use it in GitHub Desktop.
Save noginn/170266 to your computer and use it in GitHub Desktop.
ErnestMarples.com API consumer function
<?php
/**
* This file contains a simple function for consuming the ErnestMarples.com postcode
* geocoding API (http://ernestmarples.com/). The original function was written
* by Stuart Harrison, I just adapted it to not rely on file_get_contents.
*
* @author Tom Graham (adapted from Stuart Harrison's function)
* @link http://www.pezholio.co.uk/2009/07/ernest-marples-php-helper-function/
*/
/**
* Returns the latitude/longitude coordinate for a given postcode using the
* ErnestMarples.com API.
*
* The result is returned as an array with the data in the following keys:
* 0 => postcode
* 1 => latitude coordinate
* 2 => longitude coordinate
*
* If the service is unresponsive or sends an invalid response then NULL will be
* returned.
*
* @param string $postcode
* @return array
* @author Tom Graham
*/
function ernest_marples($postcode)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://ernestmarples.com?f=csv&p=' . urlencode($postcode));
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 5);
$response = curl_exec($curl);
curl_close($curl);
if (strpos($response, '<!DOCTYPE') !== false) {
// Invalid postcode, HTML page returned
return null;
}
$result = explode(',', $response);
if (count($result) !== 3) {
// Expected <postcode>,<latitude>,<longitude>
return null;
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment