Working with UK Postcodes in PHP

6th March 2014 | Tags:

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 service

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;

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

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

Because the UkPost­code class utilises Geot­ools, you can do all sorts of geo-​related stuff with the post­codes (using getCoordinate()) such as find­ing the dis­tance between a point and a post­code, or between two postcodes.

The source is on Github.


No comments yet.

Links and images are allowed, but please note that rel="nofollow" will be automactically appended to any links.