Working with UK Postcodes in PHP

Posted 6th March 2014

I’ve cre­ated a sim­ple pack­age for work­ing with UK Post­codes. It con­tains two prin­ci­ple components:

  1. A sim­ple class to encap­su­late UK Postcodes
  2. A wrap­per to this web ser­vice

The post­code class can be used for:

  • val­i­dat­ing postcodes
  • for­mat­ting them, e.g. “sw1a2aa” -> “SW1A 2AA
  • get­ting the out­code (the first part of a post­code; e.g. M1, SW1A, GL9)

The meat and bones of the pack­age, though, is the web ser­vice. Most notably, it allows you to take a post­code, and find out its lat­i­tude and lon­gi­tude. Here’s an exam­ple 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