Working with UK Postcodes in PHP

6th March 2014

I've created a simple package for working with UK Postcodes. It contains two principle components:

  1. A simple class to encapsulate UK Postcodes
  2. A wrapper to this web service

The postcode class can be used for:

  • validating postcodes
  • formatting them, e.g. "sw1a2aa" -> "SW1A 2AA"
  • getting the outcode (the first part of a postcode; e.g. M1, SW1A, GL9)

The meat and bones of the package, though, is the web service. Most notably, it allows you to take a postcode, and find out its latitude and longitude. Here's an example of how it's used:

// Create the client
$client = new Lukaswhite\UkPostcodes\UkPostcodesClient();       

// Call the web service
$postcode = $client->postcode('sw1a2aa');

print get_class($postcode);
// Lukaswhite\UkPostcodes\UkPostcode

print $postcode->formatted();
// SW1A 2AA

print get_class($postcode->getCoordinate());
// League\Geotools\Coordinate\Coordinate

print $postcode->getCoordinate()->getLatitude();
// 51.503539898876

print $postcode->getCoordinate()->getLongitude();
// -0.12768084037293

print get_class($postcode->getCoordinate()->getEllipsoid());
// League\Geotools\Coordinate\Ellipsoid 

print $postcode->council->title;
// City of Westminster

print $postcode->council->code;
// E09000033

print $postcode->council->uri;
// http://statistics.data.gov.uk/id/statistical-geography/E09000033

print $postcode->ward->title;
// St. James's

print $postcode->constituency->title;
// Cities of London and Westminster

Because the UkPostcode class utilises Geotools, you can do all sorts of geo-related stuff with the postcodes (using getCoordinate()) such as finding the distance between a point and a postcode, or between two postcodes.

The source is on Github.