Skip to content
Browse files

First commit

  • Loading branch information...
0 parents commit 4dacc45102042216f8a3d9abadf53eb4e088d8df @pezholio committed Apr 9, 2010
Showing with 1,486 additions and 0 deletions.
  1. +8 −0 .htaccess
  2. +37 −0 404.php
  3. +3 −0 README
  4. +47 −0 api.php
  5. +11 −0 csv.php
  6. +48 −0 distance.php
  7. +104 −0 index.php
  8. +38 −0 json.php
  9. +25 −0 kml.php
  10. +779 −0 phpcoord-2.3.php
  11. +89 −0 postcode.php
  12. BIN postcodes.sql.gz
  13. +49 −0 rdf.php
  14. +95 −0 result.php
  15. +47 −0 xml.php
  16. +106 −0 xmlparse.php
8 .htaccess
@@ -0,0 +1,8 @@
+RewriteEngine on
+RewriteBase /
+RewriteRule ^postcode/(all)\.?(xml|json|rdf|csv)?$ all.php?format=$2 [NC]
+RewriteCond %{QUERY_STRING} callback=(.*)
+RewriteRule ^postcode/([a-z0-9]+)\.?(xml|json|rdf|csv)?$ postcode.php?postcode=$1&format=$2&callback=%1 [NC]
+RewriteRule ^postcode/([a-z0-9]+)\.?(xml|json|rdf|csv)?$ postcode.php?postcode=$1&format=$2 [NC]
+RewriteRule ^latlng/([0-9.]+),([-0-9.]+)(\.xml|\.json|\.rdf|\.csv)?$ postcode.php?lat=$1&lng=$2&format=$3&callback=%1 [NC]
+RewriteRule ^latlng/([0-9.]+),([-0-9.]+)(\.xml|\.json|\.rdf|\.csv)?$ postcode.php?lat=$1&lng=$2&format=$3 [NC]
37 404.php
@@ -0,0 +1,37 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
+<head>
+ <title>UK Postcodes | Resource not found</title>
+ <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/grid.css" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/typography.css" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/forms.css" />
+<link type="text/css" rel="stylesheet" href="http://www.uk-postcodes.com/style.css" />
+</head>
+<body>
+<div id="header">
+<h1><a href="http://www.uk-postcodes.com">UK Postcodes</a></h1>
+</div>
+
+<div id="main">
+<h2>Resource not found</h2>
+<div id="wrapper">
+<p>http://www.uk-postcodes.com/postcode/<?php echo $postcode; ?> was not found on this server.</p>
+<p>Why not try <a href="http://www.uk-postcodes.com">searching again</a>?</p>
+</div>
+</div>
+
+<div id="formats">
+<p>Created using <a href="http://www.ordnancesurvey.co.uk/oswebsite/opendata/">Ordnance Survey Open Data</a> | <a href="api.php">API</a> <img src="http://m.okfn.org/images/ok_buttons/od_80x15_blue.png" alt="Open Data" style="float:right;" /></p>
+</div>
+<script type="text/javascript">
+var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
+document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
+</script>
+<script type="text/javascript">
+try {
+var pageTracker = _gat._getTracker("UA-511839-16");
+pageTracker._trackPageview();
+} catch(err) {}</script>
+</body>
+</html>
3 README
@@ -0,0 +1,3 @@
+This is the code for UK Postcodes, an API for Codepoint Open. Shows the Latitude, Longitude, Easting, Northing and Local Authority details (county, district, ward) for a given point. Also shows nearest postcodes to a postcode and allows reverse geocoding (lat/lng to postcode).
+
+Code includes Gzipped version of the whole dataset in SQL format.
47 api.php
@@ -0,0 +1,47 @@
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
+<head>
+ <title>UK Postcodes | Open data for postcodes</title>
+ <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/grid.css" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/typography.css" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/forms.css" />
+<link type="text/css" rel="stylesheet" href="style.css" />
+</head>
+<body>
+<div id="header">
+<h1><a href="http://www.uk-postcodes.com">UK Postcodes</a></h1>
+</div>
+
+<div id="main">
+<h2>API</h2>
+<div id="wrapper">
+<p>Get the data you want simply by constructing your URLs as follows:</p>
+<h3>Return data for a postcode</h3>
+<code>http://www.uk-postcodes.com/postcode/<strong>[postcode (no space)]</strong>.<strong>['xml', 'csv', 'json'* or 'rdf']</strong></code>
+<h3>Return data for the nearest postcode to a point</h3>
+<code>http://www.uk-postcodes.com/latlng/<strong>[latitude]</strong>,<strong>[longitude]</strong>.<strong>['xml', 'csv', 'json'* or 'rdf']</strong></code>
+<h3>Return data for postcodes within x distance (miles) of a postcode or lat/lng</h3>
+<code>http://www.uk-postcodes.com/distance.php?<strong>postcode=[postcode]</strong>&<strong>distance=[distance in miles]</strong>&<strong>format=[xml|csv|json]</strong></code>
+<code>http://www.uk-postcodes.com/distance.php?<strong>lat=[latitude]</strong>&<strong>lng=[longitude]</strong>&<strong>distance=[distance in miles]</strong>&<strong>format=[xml|csv|json]</strong></code>
+<p>That's it! Be nice to the server and cache your requests!</p>
+<p><small>* If using JSON, add '?callback=<strong>[some function call]</strong>' to the url to return JSONP</small></p>
+</div>
+</div>
+
+<div id="formats">
+<p>Created using <a href="http://www.ordnancesurvey.co.uk/oswebsite/opendata/">Ordnance Survey Open Data</a> | <a href="api.php">API</a> <img src="http://m.okfn.org/images/ok_buttons/od_80x15_blue.png" alt="Open Data" style="float:right;" /></p>
+<p>Built by <a href="http://www.pezholio.co.uk">Pezholio</a></p>
+</div>
+<script type="text/javascript">
+var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
+document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
+</script>
+<script type="text/javascript">
+try {
+var pageTracker = _gat._getTracker("UA-511839-16");
+pageTracker._trackPageview();
+} catch(err) {}</script>
+</body>
+</html>
11 csv.php
@@ -0,0 +1,11 @@
+<?php
+if ($single) {
+header("Content-Disposition: attachment; filename=\"". $postcode .".csv\"");
+echo $postcode .",". $lat .",". $lng. ",". $easting .",". $northing .",". $geohash .",". $row['county'] . ",". $countytitle .",". $row['district'] .",". $districttitle .",". $row['ward'].",".$wardtitle;
+} elseif ($distance) {
+header("Content-Disposition: attachment; filename=\"".$distance." miles of ". $title .".csv\"");
+while ($row = mysql_fetch_array($result)) {
+echo $row['postcode'] .",". $row['lat'] .",". $row['lng']. ",http://www.uk-postcodes.com/postcode/". str_replace(" ", "", $row['postcode']) ."\r\n";
+}
+}
+?>
48 distance.php
@@ -0,0 +1,48 @@
+<?php
+$db_name = '';
+$db_username = '';
+$db_password = '';
+
+mysql_connect('localhost', $db_username, $db_password);
+mysql_select_db($db_name) or die(mysql_error());
+
+if ($_GET['postcode']) {
+$postcode = addslashes($_GET['postcode']);
+$result = mysql_query("SELECT * FROM postcodes WHERE REPLACE(postcode,' ','') = '$postcode'");
+$row = mysql_fetch_array($result);
+$lat = $row['lat'];
+$lng = $row['lng'];
+$postcode = $row['postcode'];
+$title = $postcode;
+} else {
+$lat = addslashes($_GET['lat']);
+$lng = addslashes($_GET['lng']);
+$title = $lat .",". $lng;
+}
+
+$distance = addslashes($_GET['distance']);
+
+$result = mysql_query("SELECT *, ( 3959 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance FROM postcodes HAVING distance <= $distance ORDER BY distance");
+
+if ($_GET['format'] == "xml") {
+header ("content-type: text/xml");
+include("xml.php");
+} elseif ($_GET['format'] == "kml") {
+header ("content-type: application/vnd.google-earth.kml+xml");
+include("kml.php");
+} elseif ($_GET['format'] == "csv") {
+header("Content-type: application/octet-stream");
+include("csv.php");
+} elseif ($_GET['format'] == "json") {
+header('Content-type: application/json');
+include("json.php");
+} elseif ($_GET['format'] == "rdf") {
+header ("Content-type: application/rdf+xml");
+include("rdf.php");
+?>
+<?php
+} else {
+header ("content-type: text/html");
+include("result.php");
+}
+?>
104 index.php
@@ -0,0 +1,104 @@
+<?php
+if ($_POST['form'] == 1) {
+header("Location: http://www.uk-postcodes.com/postcode/".str_replace(" ", "", $_POST['postcode']). $_POST['type']);
+} elseif ($_POST['form'] == 2) {
+header("Location: http://www.uk-postcodes.com/distance.php?postcode=".str_replace(" ", "", $_POST['postcode'])."&distance=". $_POST['distance'] ."&format=". $_POST['type']);
+} elseif ($_POST['form'] == 3) {
+header("Location: http://www.uk-postcodes.com/latlng/".$_POST['lat'].",".$_POST['lng']. $_POST['type']);
+}
+?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
+<head>
+ <title>UK Postcodes | Open data for postcodes</title>
+ <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/grid.css" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/typography.css" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/forms.css" />
+<link type="text/css" rel="stylesheet" href="style.css" />
+<script type="text/javascript" src="http://www.google.com/jsapi"></script>
+<script type="text/javascript">
+ google.load("jquery", "1");
+
+ google.setOnLoadCallback(function() {
+
+ $('.tab').click(function() {
+ target = this.title;
+ $('.tab').removeClass('selected');
+ $('#postcode').attr('style','display:none');
+ $('#nearest').attr('style','display:none');
+ $('#reverse').attr('style','display:none');
+ $('#'+ target).attr('style','display:block');
+ $(this).addClass('selected');
+ return false;
+ });
+
+ });
+</script>
+
+</head>
+<body>
+<div id="header">
+<h1><a href="http://www.uk-postcodes.com">UK Postcodes</a></h1>
+<ul id="tab">
+<li><a href="#postcode" title="postcode" class="tab selected">Postcode</a></li>
+<li><a href="#nearest" title="nearest" class="tab">Nearest</a></li>
+<li><a href="#reverse" title="reverse" class="tab">Reverse Geocode</a></li>
+</ul>
+<form method="post" style="display:block;" id="postcode">
+<input type="hidden" name="form" value="1" />
+<h2>Give me data for <input type="text" name="postcode" onclick="this.value=''" value="Postcode" /> in
+<select name="type">
+<option value="">HTML</option>
+<option value=".xml">XML</option>
+<option value=".csv">CSV</option>
+<option value=".json">JSON</option>
+<option value=".rdf">RDF</option>
+</select>
+format <button type="submit" class="btn" name="pc"><span><span>please</span></span></button>
+</h2>
+</form>
+<form method="post" style="display:none;" id="nearest">
+<input type="hidden" name="form" value="2" />
+<h2>Show me postcodes within <input type="text" name="distance" style="width: 30px;" value="" /> miles of <input type="text" name="postcode" onclick="this.value=''" value="Postcode" /> in
+<select name="type">
+<option value="">HTML</option>
+<option value="xml">XML</option>
+<option value="csv">CSV</option>
+<option value="json">JSON</option>
+<option value="rdf">RDF</option>
+<option value="kml">KML</option>
+</select>
+format <button type="submit" class="btn" name="nearest"><span><span>please</span></span></button>
+</h2>
+</form>
+<form method="post" style="display:none;" id="reverse">
+<input type="hidden" name="form" value="3" />
+<h2>Give me data for the nearest postcode to <input type="text" name="lat" onclick="this.value=''" value="Latitude" /> , <input type="text" name="lng" onclick="this.value=''" value="Longitude" /> in
+<select name="type">
+<option value="">HTML</option>
+<option value=".xml">XML</option>
+<option value=".csv">CSV</option>
+<option value=".json">JSON</option>
+<option value=".rdf">RDF</option>
+</select>
+format <button type="submit" class="btn" name="latlng"><span><span>please</span></span></button>
+</h2>
+</form>
+</div>
+
+<div id="formats">
+<p>Created using <a href="http://www.ordnancesurvey.co.uk/oswebsite/opendata/">Ordnance Survey Open Data</a> | <a href="api.php">API</a> <img src="http://m.okfn.org/images/ok_buttons/od_80x15_blue.png" alt="Open Data" style="float:right;" /></p>
+<p>Built by <a href="http://www.pezholio.co.uk">Pezholio</a></p>
+</div>
+<script type="text/javascript">
+var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
+document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
+</script>
+<script type="text/javascript">
+try {
+var pageTracker = _gat._getTracker("UA-511839-16");
+pageTracker._trackPageview();
+} catch(err) {}</script>
+</body>
+</html>
38 json.php
@@ -0,0 +1,38 @@
+<?php
+if ($single) {
+$result = array();
+$result['postcode'] = $row['postcode'];
+$result['geo']['lat'] = $lat;
+$result['geo']['lng'] = $lng;
+$result['geo']['easting'] = $easting;
+$result['geo']['northing'] = $northing;
+$result['geo']['geohash'] = $geohash;
+if ($row['county'] != "00") {
+$result['administrative']['county']['title'] = $countytitle;
+$result['administrative']['county']['uri'] = "http://statistics.data.gov.uk/id/local-authority/". $row['county'];
+}
+$result['administrative']['district']['title'] = $districttitle;
+$result['administrative']['district']['uri'] = "http://statistics.data.gov.uk/id/local-authority/". $row['county'] . $row['district'];
+$result['administrative']['ward']['title'] = $wardtitle;
+$result['administrative']['ward']['uri'] = "http://statistics.data.gov.uk/id/electoral-ward/". $row['county'] . $row['district'] . $row['ward'];
+
+ if ($_GET['callback']) {
+ $callback = $_GET['callback'];
+ echo $callback . '(' . json_encode($result) . ')';
+ } else {
+ echo json_encode($result);
+ }
+} elseif ($distance) {
+$json = array();
+$num = 0;
+while ($row = mysql_fetch_array($result)) {
+$json[$num]['postcode'] = $row['postcode'];
+$json[$num]['lat'] = $row['lat'];
+$json[$num]['lng'] = $row['lng'];
+$json[$num]['distance'] = $row['distance'];
+$json[$num]['uri'] = "http://www.uk-postcodes.com/postcode/". str_replace(" ", "", $row['postcode']);
+$num++;
+}
+echo json_encode($json);
+}
+?>
25 kml.php
@@ -0,0 +1,25 @@
+<?php
+if ($distance) {
+?>
+<kml xmlns="http://www.opengis.net/kml/2.2">
+<Document>
+ <name>UK Postcodes</name>
+ <description>Postcodes within <?php echo $distance; ?> miles of <?php echo $title; ?></description>
+<?php
+while ($row = mysql_fetch_array($result)) {
+?>
+ <Placemark>
+ <name><?php echo $row['postcode']; ?></name>
+ <description>
+ <![CDATA[
+<a href="http://www.uk-postcodes.com/postcode/<?php echo str_replace(" ", "", $row['postcode']); ?>"><?php echo $row['postcode']; ?></a>
+ ]]>
+</description>
+ <Point>
+ <coordinates><?php echo $row['lng']; ?>, <?php echo $row['lat']; ?></coordinates>
+ </Point>
+ </Placemark>
+<?php } ?>
+</Document>
+</kml>
+<?php } ?>
779 phpcoord-2.3.php
@@ -0,0 +1,779 @@
+<?php
+
+ //--------------------------------------------------------------------------
+ // PHPcoord
+ // phpcoord.php
+ //
+ // (c) 2005 Jonathan Stott
+ //
+ // Created on 11-Aug-2005
+ //
+ // 2.3 - 24 Aug 2006
+ // - Changed OSRef->toSixFigureString() so that the eastings and northings
+ // are rounded rather than floored.
+ // 2.2 - 11 Feb 2006
+ // - Used different algorithm for calculating distance between latitudes
+ // and longitudes - fixes a number of problems with distance calculations
+ // 2.1 - 22 Dec 2005
+ // - Added getOSRefFromSixFigureReference function
+ // 2.0 - 21 Dec 2005
+ // - Completely different object design - conversion functions now through
+ // objects rather than static functions
+ // - Updated comments and documentation
+ // 1.1 - 11 Sep 2005
+ // - Added OSGB36/WGS84 data conversions
+ // 1.0 - 11 Aug 2005
+ // - Initial version
+ //--------------------------------------------------------------------------
+
+
+ // ================================================================== LatLng
+
+ class LatLng {
+
+ var $lat;
+ var $lng;
+
+
+ /**
+ * Create a new LatLng object from the given latitude and longitude
+ *
+ * @param lat latitude
+ * @param lng longitude
+ */
+ function LatLng($lat, $lng) {
+ $this->lat = $lat;
+ $this->lng = $lng;
+ }
+
+
+ /**
+ * Return a string representation of this LatLng object
+ *
+ * @return a string representation of this LatLng object
+ */
+ function toString() {
+ return "(" . $this->lat . ", " . $this->lng . ")";
+ }
+
+
+ /**
+ * Calculate the surface distance between this LatLng object and the one
+ * passed in as a parameter.
+ *
+ * @param to a LatLng object to measure the surface distance to
+ * @return the surface distance
+ */
+ function distance($to) {
+ $er = 6366.707;
+
+ $latFrom = deg2rad($this->lat);
+ $latTo = deg2rad($to->lat);
+ $lngFrom = deg2rad($this->lng);
+ $lngTo = deg2rad($to->lng);
+
+ $x1 = $er * cos($lngFrom) * sin($latFrom);
+ $y1 = $er * sin($lngFrom) * sin($latFrom);
+ $z1 = $er * cos($latFrom);
+
+ $x2 = $er * cos($lngTo) * sin($latTo);
+ $y2 = $er * sin($lngTo) * sin($latTo);
+ $z2 = $er * cos($latTo);
+
+ $d = acos(sin($latFrom)*sin($latTo) + cos($latFrom)*cos($latTo)*cos($lngTo-$lngFrom)) * $er;
+
+ return $d;
+ }
+
+
+ /**
+ * Convert this LatLng object from OSGB36 datum to WGS84 datum.
+ */
+ function OSGB36ToWGS84() {
+ $airy1830 = new RefEll(6377563.396, 6356256.909);
+ $a = $airy1830->maj;
+ $b = $airy1830->min;
+ $eSquared = $airy1830->ecc;
+ $phi = deg2rad($this->lat);
+ $lambda = deg2rad($this->lng);
+ $v = $a / (sqrt(1 - $eSquared * sinSquared($phi)));
+ $H = 0; // height
+ $x = ($v + $H) * cos($phi) * cos($lambda);
+ $y = ($v + $H) * cos($phi) * sin($lambda);
+ $z = ((1 - $eSquared) * $v + $H) * sin($phi);
+
+ $tx = 446.448;
+ $ty = -124.157;
+ $tz = 542.060;
+ $s = -0.0000204894;
+ $rx = deg2rad( 0.00004172222);
+ $ry = deg2rad( 0.00006861111);
+ $rz = deg2rad( 0.00023391666);
+
+ $xB = $tx + ($x * (1 + $s)) + (-$rx * $y) + ($ry * $z);
+ $yB = $ty + ($rz * $x) + ($y * (1 + $s)) + (-$rx * $z);
+ $zB = $tz + (-$ry * $x) + ($rx * $y) + ($z * (1 + $s));
+
+ $wgs84 = new RefEll(6378137.000, 6356752.3141);
+ $a = $wgs84->maj;
+ $b = $wgs84->min;
+ $eSquared = $wgs84->ecc;
+
+ $lambdaB = rad2deg(atan($yB / $xB));
+ $p = sqrt(($xB * $xB) + ($yB * $yB));
+ $phiN = atan($zB / ($p * (1 - $eSquared)));
+ for ($i = 1; $i < 10; $i++) {
+ $v = $a / (sqrt(1 - $eSquared * sinSquared($phiN)));
+ $phiN1 = atan(($zB + ($eSquared * $v * sin($phiN))) / $p);
+ $phiN = $phiN1;
+ }
+
+ $phiB = rad2deg($phiN);
+
+ $this->lat = $phiB;
+ $this->lng = $lambdaB;
+ }
+
+
+ /**
+ * Convert this LatLng object from WGS84 datum to OSGB36 datum.
+ */
+ function WGS84ToOSGB36() {
+ $wgs84 = new RefEll(6378137.000, 6356752.3141);
+ $a = $wgs84->maj;
+ $b = $wgs84->min;
+ $eSquared = $wgs84->ecc;
+ $phi = deg2rad($this->lat);
+ $lambda = deg2rad($this->lng);
+ $v = $a / (sqrt(1 - $eSquared * sinSquared($phi)));
+ $H = 0; // height
+ $x = ($v + $H) * cos($phi) * cos($lambda);
+ $y = ($v + $H) * cos($phi) * sin($lambda);
+ $z = ((1 - $eSquared) * $v + $H) * sin($phi);
+
+ $tx = -446.448;
+ $ty = 124.157;
+ $tz = -542.060;
+ $s = 0.0000204894;
+ $rx = deg2rad(-0.00004172222);
+ $ry = deg2rad(-0.00006861111);
+ $rz = deg2rad(-0.00023391666);
+
+ $xB = $tx + ($x * (1 + $s)) + (-$rx * $y) + ($ry * $z);
+ $yB = $ty + ($rz * $x) + ($y * (1 + $s)) + (-$rx * $z);
+ $zB = $tz + (-$ry * $x) + ($rx * $y) + ($z * (1 + $s));
+
+ $airy1830 = new RefEll(6377563.396, 6356256.909);
+ $a = $airy1830->maj;
+ $b = $airy1830->min;
+ $eSquared = $airy1830->ecc;
+
+ $lambdaB = rad2deg(atan($yB / $xB));
+ $p = sqrt(($xB * $xB) + ($yB * $yB));
+ $phiN = atan($zB / ($p * (1 - $eSquared)));
+ for ($i = 1; $i < 10; $i++) {
+ $v = $a / (sqrt(1 - $eSquared * sinSquared($phiN)));
+ $phiN1 = atan(($zB + ($eSquared * $v * sin($phiN))) / $p);
+ $phiN = $phiN1;
+ }
+
+ $phiB = rad2deg($phiN);
+
+ $this->lat = $phiB;
+ $this->lng = $lambdaB;
+ }
+
+
+ /**
+ * Convert this LatLng object into an OSGB grid reference. Note that this
+ * function does not take into account the bounds of the OSGB grid -
+ * beyond the bounds of the OSGB grid, the resulting OSRef object has no
+ * meaning
+ *
+ * @return the converted OSGB grid reference
+ */
+ function toOSRef() {
+ $airy1830 = new RefEll(6377563.396, 6356256.909);
+ $OSGB_F0 = 0.9996012717;
+ $N0 = -100000.0;
+ $E0 = 400000.0;
+ $phi0 = deg2rad(49.0);
+ $lambda0 = deg2rad(-2.0);
+ $a = $airy1830->maj;
+ $b = $airy1830->min;
+ $eSquared = $airy1830->ecc;
+ $phi = deg2rad($this->lat);
+ $lambda = deg2rad($this->lng);
+ $E = 0.0;
+ $N = 0.0;
+ $n = ($a - $b) / ($a + $b);
+ $v = $a * $OSGB_F0 * pow(1.0 - $eSquared * sinSquared($phi), -0.5);
+ $rho =
+ $a * $OSGB_F0 * (1.0 - $eSquared) * pow(1.0 - $eSquared * sinSquared($phi), -1.5);
+ $etaSquared = ($v / $rho) - 1.0;
+ $M =
+ ($b * $OSGB_F0)
+ * (((1 + $n + ((5.0 / 4.0) * $n * $n) + ((5.0 / 4.0) * $n * $n * $n))
+ * ($phi - $phi0))
+ - (((3 * $n) + (3 * $n * $n) + ((21.0 / 8.0) * $n * $n * $n))
+ * sin($phi - $phi0)
+ * cos($phi + $phi0))
+ + ((((15.0 / 8.0) * $n * $n) + ((15.0 / 8.0) * $n * $n * $n))
+ * sin(2.0 * ($phi - $phi0))
+ * cos(2.0 * ($phi + $phi0)))
+ - (((35.0 / 24.0) * $n * $n * $n)
+ * sin(3.0 * ($phi - $phi0))
+ * cos(3.0 * ($phi + $phi0))));
+ $I = $M + $N0;
+ $II = ($v / 2.0) * sin($phi) * cos($phi);
+ $III =
+ ($v / 24.0)
+ * sin($phi)
+ * pow(cos($phi), 3.0)
+ * (5.0 - tanSquared($phi) + (9.0 * $etaSquared));
+ $IIIA =
+ ($v / 720.0)
+ * sin($phi)
+ * pow(cos($phi), 5.0)
+ * (61.0 - (58.0 * tanSquared($phi)) + pow(tan($phi), 4.0));
+ $IV = $v * cos($phi);
+ $V = ($v / 6.0) * pow(cos($phi), 3.0) * (($v / $rho) - tanSquared($phi));
+ $VI =
+ ($v / 120.0)
+ * pow(cos($phi), 5.0)
+ * (5.0
+ - (18.0 * tanSquared($phi))
+ + (pow(tan($phi), 4.0))
+ + (14 * $etaSquared)
+ - (58 * tanSquared($phi) * $etaSquared));
+
+ $N =
+ $I
+ + ($II * pow($lambda - $lambda0, 2.0))
+ + ($III * pow($lambda - $lambda0, 4.0))
+ + ($IIIA * pow($lambda - $lambda0, 6.0));
+ $E =
+ $E0
+ + ($IV * ($lambda - $lambda0))
+ + ($V * pow($lambda - $lambda0, 3.0))
+ + ($VI * pow($lambda - $lambda0, 5.0));
+
+ return new OSRef($E, $N);
+ }
+
+
+ /**
+ * Convert a latitude and longitude to an UTM reference
+ *
+ * @return the converted UTM reference
+ */
+ function toUTMRef() {
+ $wgs84 = new RefEll(6378137, 6356752.314);
+ $UTM_F0 = 0.9996;
+ $a = $wgs84->maj;
+ $eSquared = $wgs84->ecc;
+ $longitude = $this->lng;
+ $latitude = $this->lat;
+
+ $latitudeRad = $latitude * (pi() / 180.0);
+ $longitudeRad = $longitude * (pi() / 180.0);
+ $longitudeZone = (int) (($longitude + 180.0) / 6.0) + 1;
+
+ // Special zone for Norway
+ if ($latitude >= 56.0
+ && $latitude < 64.0
+ && $longitude >= 3.0
+ && $longitude < 12.0) {
+ $longitudeZone = 32;
+ }
+
+ // Special zones for Svalbard
+ if ($latitude >= 72.0 && $latitude < 84.0) {
+ if ($longitude >= 0.0 && $longitude < 9.0) {
+ $longitudeZone = 31;
+ } else if ($longitude >= 9.0 && $longitude < 21.0) {
+ $longitudeZone = 33;
+ } else if ($longitude >= 21.0 && $longitude < 33.0) {
+ $longitudeZone = 35;
+ } else if ($longitude >= 33.0 && $longitude < 42.0) {
+ $longitudeZone = 37;
+ }
+ }
+
+ $longitudeOrigin = ($longitudeZone - 1) * 6 - 180 + 3;
+ $longitudeOriginRad = $longitudeOrigin * (pi() / 180.0);
+
+ $UTMZone = getUTMLatitudeZoneLetter($latitude);
+
+ $ePrimeSquared = ($eSquared) / (1 - $eSquared);
+
+ $n = $a / sqrt(1 - $eSquared * sin($latitudeRad) * sin($latitudeRad));
+ $t = tan($latitudeRad) * tan($latitudeRad);
+ $c = $ePrimeSquared * cos($latitudeRad) * cos($latitudeRad);
+ $A = cos($latitudeRad) * ($longitudeRad - $longitudeOriginRad);
+
+ $M =
+ $a
+ * ((1
+ - $eSquared / 4
+ - 3 * $eSquared * $eSquared / 64
+ - 5 * $eSquared * $eSquared * $eSquared / 256)
+ * $latitudeRad
+ - (3 * $eSquared / 8
+ + 3 * $eSquared * $eSquared / 32
+ + 45 * $eSquared * $eSquared * $eSquared / 1024)
+ * sin(2 * $latitudeRad)
+ + (15 * $eSquared * $eSquared / 256
+ + 45 * $eSquared * $eSquared * $eSquared / 1024)
+ * sin(4 * $latitudeRad)
+ - (35 * $eSquared * $eSquared * $eSquared / 3072)
+ * sin(6 * $latitudeRad));
+
+ $UTMEasting =
+ (double) ($UTM_F0
+ * $n
+ * ($A
+ + (1 - $t + $c) * pow($A, 3.0) / 6
+ + (5 - 18 * $t + $t * $t + 72 * $c - 58 * $ePrimeSquared)
+ * pow($A, 5.0)
+ / 120)
+ + 500000.0);
+
+ $UTMNorthing =
+ (double) ($UTM_F0
+ * ($M
+ + $n
+ * tan($latitudeRad)
+ * ($A * $A / 2
+ + (5 - $t + (9 * $c) + (4 * $c * $c)) * pow($A, 4.0) / 24
+ + (61 - (58 * $t) + ($t * $t) + (600 * $c) - (330 * $ePrimeSquared))
+ * pow($A, 6.0)
+ / 720)));
+
+ // Adjust for the southern hemisphere
+ if ($latitude < 0) {
+ $UTMNorthing += 10000000.0;
+ }
+
+ return new UTMRef($UTMEasting, $UTMNorthing, $UTMZone, $longitudeZone);
+ }
+ }
+
+
+ // =================================================================== OSRef
+
+ // References given with OSRef are accurate to 1m.
+ class OSRef {
+
+ var $easting;
+ var $northing;
+
+
+ /**
+ * Create a new OSRef object representing an OSGB grid reference. Note
+ * that the parameters for this constructor require eastings and
+ * northings with 1m accuracy and need to be absolute with respect to
+ * the whole of the British Grid. For example, to create an OSRef
+ * object from the six-figure grid reference TG514131, the easting would
+ * be 651400 and the northing would be 313100.
+ *
+ * Grid references with accuracy greater than 1m can be represented
+ * using floating point values for the easting and northing. For example,
+ * a value representing an easting or northing accurate to 1mm would be
+ * given as 651400.0001.
+ *
+ * @param easting the easting of the reference (with 1m accuracy)
+ * @param northing the northing of the reference (with 1m accuracy)
+ */
+ function OSRef($easting, $northing) {
+ $this->easting = $easting;
+ $this->northing = $northing;
+ }
+
+
+ /**
+ * Convert this grid reference into a string showing the exact values
+ * of the easting and northing.
+ *
+ * @return
+ */
+ function toString() {
+ return "(" . $this->easting . ", " . $this->northing . ")";
+ }
+
+ function toSplitString() {
+ $result['easting'] = $this->easting;
+ $result['northing'] = $this->northing;
+ return $result;
+ }
+
+
+ /**
+ * Convert this grid reference into a string using a standard six-figure
+ * grid reference including the two-character designation for the 100km
+ * square. e.g. TG514131.
+ *
+ * @return
+ */
+ function toSixFigureString() {
+ $hundredkmE = floor($this->easting / 100000);
+ $hundredkmN = floor($this->northing / 100000);
+ $firstLetter = "";
+ if ($hundredkmN < 5) {
+ if ($hundredkmE < 5) {
+ $firstLetter = "S";
+ } else {
+ $firstLetter = "T";
+ }
+ } else if ($hundredkmN < 10) {
+ if ($hundredkmE < 5) {
+ $firstLetter = "N";
+ } else {
+ $firstLetter = "O";
+ }
+ } else {
+ $firstLetter = "H";
+ }
+
+ $secondLetter = "";
+ $index = 65 + ((4 - ($hundredkmN % 5)) * 5) + ($hundredkmE % 5);
+ $ti = $index;
+ if ($index >= 73) $index++;
+ $secondLetter = chr($index);
+
+ $e = round(($this->easting - (100000 * $hundredkmE)) / 100);
+ $n = round(($this->northing - (100000 * $hundredkmN)) / 100);
+
+ return sprintf("%s%s%03d%03d", $firstLetter, $secondLetter, $e, $n);
+ }
+
+
+ /**
+ * Convert this grid reference into a latitude and longitude
+ *
+ * @return
+ */
+ function toLatLng() {
+ $airy1830 = new RefEll(6377563.396, 6356256.909);
+ $OSGB_F0 = 0.9996012717;
+ $N0 = -100000.0;
+ $E0 = 400000.0;
+ $phi0 = deg2rad(49.0);
+ $lambda0 = deg2rad(-2.0);
+ $a = $airy1830->maj;
+ $b = $airy1830->min;
+ $eSquared = $airy1830->ecc;
+ $phi = 0.0;
+ $lambda = 0.0;
+ $E = $this->easting;
+ $N = $this->northing;
+ $n = ($a - $b) / ($a + $b);
+ $M = 0.0;
+ $phiPrime = (($N - $N0) / ($a * $OSGB_F0)) + $phi0;
+ do {
+ $M =
+ ($b * $OSGB_F0)
+ * (((1 + $n + ((5.0 / 4.0) * $n * $n) + ((5.0 / 4.0) * $n * $n * $n))
+ * ($phiPrime - $phi0))
+ - (((3 * $n) + (3 * $n * $n) + ((21.0 / 8.0) * $n * $n * $n))
+ * sin($phiPrime - $phi0)
+ * cos($phiPrime + $phi0))
+ + ((((15.0 / 8.0) * $n * $n) + ((15.0 / 8.0) * $n * $n * $n))
+ * sin(2.0 * ($phiPrime - $phi0))
+ * cos(2.0 * ($phiPrime + $phi0)))
+ - (((35.0 / 24.0) * $n * $n * $n)
+ * sin(3.0 * ($phiPrime - $phi0))
+ * cos(3.0 * ($phiPrime + $phi0))));
+ $phiPrime += ($N - $N0 - $M) / ($a * $OSGB_F0);
+ } while (($N - $N0 - $M) >= 0.001);
+ $v = $a * $OSGB_F0 * pow(1.0 - $eSquared * sinSquared($phiPrime), -0.5);
+ $rho =
+ $a
+ * $OSGB_F0
+ * (1.0 - $eSquared)
+ * pow(1.0 - $eSquared * sinSquared($phiPrime), -1.5);
+ $etaSquared = ($v / $rho) - 1.0;
+ $VII = tan($phiPrime) / (2 * $rho * $v);
+ $VIII =
+ (tan($phiPrime) / (24.0 * $rho * pow($v, 3.0)))
+ * (5.0
+ + (3.0 * tanSquared($phiPrime))
+ + $etaSquared
+ - (9.0 * tanSquared($phiPrime) * $etaSquared));
+ $IX =
+ (tan($phiPrime) / (720.0 * $rho * pow($v, 5.0)))
+ * (61.0
+ + (90.0 * tanSquared($phiPrime))
+ + (45.0 * tanSquared($phiPrime) * tanSquared($phiPrime)));
+ $X = sec($phiPrime) / $v;
+ $XI =
+ (sec($phiPrime) / (6.0 * $v * $v * $v))
+ * (($v / $rho) + (2 * tanSquared($phiPrime)));
+ $XII =
+ (sec($phiPrime) / (120.0 * pow($v, 5.0)))
+ * (5.0
+ + (28.0 * tanSquared($phiPrime))
+ + (24.0 * tanSquared($phiPrime) * tanSquared($phiPrime)));
+ $XIIA =
+ (sec($phiPrime) / (5040.0 * pow($v, 7.0)))
+ * (61.0
+ + (662.0 * tanSquared($phiPrime))
+ + (1320.0 * tanSquared($phiPrime) * tanSquared($phiPrime))
+ + (720.0
+ * tanSquared($phiPrime)
+ * tanSquared($phiPrime)
+ * tanSquared($phiPrime)));
+ $phi =
+ $phiPrime
+ - ($VII * pow($E - $E0, 2.0))
+ + ($VIII * pow($E - $E0, 4.0))
+ - ($IX * pow($E - $E0, 6.0));
+ $lambda =
+ $lambda0
+ + ($X * ($E - $E0))
+ - ($XI * pow($E - $E0, 3.0))
+ + ($XII * pow($E - $E0, 5.0))
+ - ($XIIA * pow($E - $E0, 7.0));
+
+ return new LatLng(rad2deg($phi), rad2deg($lambda));
+ }
+ }
+
+
+ // ================================================================== UTMRef
+
+ class UTMRef {
+
+ var $easting;
+ var $northing;
+ var $latZone;
+ var $lngZone;
+
+
+ /**
+ * Create a new object representing a UTM reference.
+ *
+ * @param easting
+ * @param northing
+ * @param latZone
+ * @param lngZone
+ */
+ function UTMRef($easting, $northing, $latZone, $lngZone) {
+ $this->easting = $easting;
+ $this->northing = $northing;
+ $this->latZone = $latZone;
+ $this->lngZone = $lngZone;
+ }
+
+
+ /**
+ * Return a string representation of this UTM reference
+ *
+ * @return
+ */
+ function toString() {
+ return $this->lngZone . $this->latZone . " " .
+ $this->easting . " " . $this->northing;
+ }
+
+
+ /**
+ * Convert this UTM reference to a latitude and longitude
+ *
+ * @return the converted latitude and longitude
+ */
+ function toLatLng() {
+ $wgs84 = new RefEll(6378137, 6356752.314);
+ $UTM_F0 = 0.9996;
+ $a = $wgs84->maj;
+ $eSquared = $wgs84->ecc;
+ $ePrimeSquared = $eSquared / (1.0 - $eSquared);
+ $e1 = (1 - sqrt(1 - $eSquared)) / (1 + sqrt(1 - $eSquared));
+ $x = $this->easting - 500000.0;;
+ $y = $this->northing;
+ $zoneNumber = $this->lngZone;
+ $zoneLetter = $this->latZone;
+
+ $longitudeOrigin = ($zoneNumber - 1.0) * 6.0 - 180.0 + 3.0;
+
+ // Correct y for southern hemisphere
+ if ((ord($zoneLetter) - ord("N")) < 0) {
+ $y -= 10000000.0;
+ }
+
+ $m = $y / $UTM_F0;
+ $mu =
+ $m
+ / ($a
+ * (1.0
+ - $eSquared / 4.0
+ - 3.0 * $eSquared * $eSquared / 64.0
+ - 5.0
+ * pow($eSquared, 3.0)
+ / 256.0));
+
+ $phi1Rad =
+ $mu
+ + (3.0 * $e1 / 2.0 - 27.0 * pow($e1, 3.0) / 32.0) * sin(2.0 * $mu)
+ + (21.0 * $e1 * $e1 / 16.0 - 55.0 * pow($e1, 4.0) / 32.0)
+ * sin(4.0 * $mu)
+ + (151.0 * pow($e1, 3.0) / 96.0) * sin(6.0 * $mu);
+
+ $n =
+ $a
+ / sqrt(1.0 - $eSquared * sin($phi1Rad) * sin($phi1Rad));
+ $t = tan($phi1Rad) * tan($phi1Rad);
+ $c = $ePrimeSquared * cos($phi1Rad) * cos($phi1Rad);
+ $r =
+ $a
+ * (1.0 - $eSquared)
+ / pow(
+ 1.0 - $eSquared * sin($phi1Rad) * sin($phi1Rad),
+ 1.5);
+ $d = $x / ($n * $UTM_F0);
+
+ $latitude = (
+ $phi1Rad
+ - ($n * tan($phi1Rad) / $r)
+ * ($d * $d / 2.0
+ - (5.0
+ + (3.0 * $t)
+ + (10.0 * $c)
+ - (4.0 * $c * $c)
+ - (9.0 * $ePrimeSquared))
+ * pow($d, 4.0)
+ / 24.0
+ + (61.0
+ + (90.0 * $t)
+ + (298.0 * $c)
+ + (45.0 * $t * $t)
+ - (252.0 * $ePrimeSquared)
+ - (3.0 * $c * $c))
+ * pow($d, 6.0)
+ / 720.0)) * (180.0 / pi());
+
+ $longitude = $longitudeOrigin + (
+ ($d
+ - (1.0 + 2.0 * $t + $c) * pow($d, 3.0) / 6.0
+ + (5.0
+ - (2.0 * $c)
+ + (28.0 * $t)
+ - (3.0 * $c * $c)
+ + (8.0 * $ePrimeSquared)
+ + (24.0 * $t * $t))
+ * pow($d, 5.0)
+ / 120.0)
+ / cos($phi1Rad)) * (180.0 / pi());
+
+ return new LatLng($latitude, $longitude);
+ }
+ }
+
+
+ // ================================================================== RefEll
+
+ class RefEll {
+
+ var $maj;
+ var $min;
+ var $ecc;
+
+
+ /**
+ * Create a new RefEll object to represent a reference ellipsoid
+ *
+ * @param maj the major axis
+ * @param min the minor axis
+ */
+ function RefEll($maj, $min) {
+ $this->maj = $maj;
+ $this->min = $min;
+ $this->ecc = (($maj * $maj) - ($min * $min)) / ($maj * $maj);
+ }
+ }
+
+
+ // ================================================== Mathematical Functions
+
+ function sinSquared($x) {
+ return sin($x) * sin($x);
+ }
+
+ function cosSquared($x) {
+ return cos($x) * cos($x);
+ }
+
+ function tanSquared($x) {
+ return tan($x) * tan($x);
+ }
+
+ function sec($x) {
+ return 1.0 / cos($x);
+ }
+
+
+ /**
+ * Take a string formatted as a six-figure OS grid reference (e.g.
+ * "TG514131") and return a reference to an OSRef object that represents
+ * that grid reference. The first character must be H, N, S, O or T.
+ * The second character can be any uppercase character from A through Z
+ * excluding I.
+ *
+ * @param ref
+ * @return
+ * @since 2.1
+ */
+ function getOSRefFromSixFigureReference($ref) {
+ $char1 = substr($ref, 0, 1);
+ $char2 = substr($ref, 1, 1);
+ $east = substr($ref, 2, 3) * 100;
+ $north = substr($ref, 5, 3) * 100;
+ if ($char1 == 'H') {
+ $north += 1000000;
+ } else if ($char1 == 'N') {
+ $north += 500000;
+ } else if ($char1 == 'O') {
+ $north += 500000;
+ $east += 500000;
+ } else if ($char1 == 'T') {
+ $east += 500000;
+ }
+ $char2ord = ord($char2);
+ if ($char2ord > 73) $char2ord--; // Adjust for no I
+ $nx = (($char2ord - 65) % 5) * 100000;
+ $ny = (4 - floor(($char2ord - 65) / 5)) * 100000;
+ return new OSRef($east + $nx, $north + $ny);
+ }
+
+
+ /**
+ * Work out the UTM latitude zone from the latitude
+ *
+ * @param latitude
+ * @return
+ */
+ function getUTMLatitudeZoneLetter($latitude) {
+ if ((84 >= $latitude) && ($latitude >= 72)) return "X";
+ else if (( 72 > $latitude) && ($latitude >= 64)) return "W";
+ else if (( 64 > $latitude) && ($latitude >= 56)) return "V";
+ else if (( 56 > $latitude) && ($latitude >= 48)) return "U";
+ else if (( 48 > $latitude) && ($latitude >= 40)) return "T";
+ else if (( 40 > $latitude) && ($latitude >= 32)) return "S";
+ else if (( 32 > $latitude) && ($latitude >= 24)) return "R";
+ else if (( 24 > $latitude) && ($latitude >= 16)) return "Q";
+ else if (( 16 > $latitude) && ($latitude >= 8)) return "P";
+ else if (( 8 > $latitude) && ($latitude >= 0)) return "N";
+ else if (( 0 > $latitude) && ($latitude >= -8)) return "M";
+ else if (( -8 > $latitude) && ($latitude >= -16)) return "L";
+ else if ((-16 > $latitude) && ($latitude >= -24)) return "K";
+ else if ((-24 > $latitude) && ($latitude >= -32)) return "J";
+ else if ((-32 > $latitude) && ($latitude >= -40)) return "H";
+ else if ((-40 > $latitude) && ($latitude >= -48)) return "G";
+ else if ((-48 > $latitude) && ($latitude >= -56)) return "F";
+ else if ((-56 > $latitude) && ($latitude >= -64)) return "E";
+ else if ((-64 > $latitude) && ($latitude >= -72)) return "D";
+ else if ((-72 > $latitude) && ($latitude >= -80)) return "C";
+ else return 'Z';
+ }
+
+?>
89 postcode.php
@@ -0,0 +1,89 @@
+<?php
+require_once("xmlparse.php");
+require_once("phpcoord-2.3.php");
+
+$db_name = '';
+$db_username = '';
+$db_password = '';
+
+mysql_connect('localhost', $db_username, $db_password);
+mysql_select_db($db_name) or die(mysql_error());
+
+if ($_GET['postcode']) {
+
+ $postcode = $_GET['postcode'];
+ $single = TRUE;
+
+if ($postcode != strtoupper($postcode)) {
+ header ('HTTP/1.1 301 Moved Permanently');
+
+ if (strlen($_GET['format']) > 0) {
+ header("Location: http://www.uk-postcodes.com/postcode/".strtoupper($postcode).".".$_GET['format']);
+ } else {
+ header("Location: http://www.uk-postcodes.com/postcode/".strtoupper($postcode));
+ }
+}
+
+ $result = mysql_query("SELECT * FROM postcodes WHERE REPLACE(postcode,' ','') = '$postcode'");
+
+} else {
+ $lat = $_GET['lat'];
+ $lng = $_GET['lng'];
+ $result = mysql_query("SELECT *, ( 3959 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance FROM postcodes ORDER BY distance LIMIT 0,1");
+ $_GET['format'] = str_replace(".", "", $_GET['format']);
+}
+
+$num_rows = mysql_num_rows($result);
+
+if ($num_rows == 0) {
+ header("HTTP/1.0 404 Not Found");
+ include("404.php");
+} else {
+
+ $row = mysql_fetch_array($result);
+
+ $lat = $row['lat'];
+ $lng = $row['lng'];
+
+ $ll2w = new LatLng($lat, $lng);
+ $ll2w->WGS84ToOSGB36();
+ $os2w = $ll2w->toOSRef();
+ $eastingnorthing = $os2w->toSplitString();
+
+ $easting = $eastingnorthing['easting'];
+ $northing = $eastingnorthing['northing'];
+
+ $geohash = file_get_contents("http://geohash.org?q=".$lat.",".$lng."&format=url");
+
+if ($row['county'] != "00") {
+$county = get_xml("http://statistics.data.gov.uk/doc/local-authority/". $row['county'] .".rdf");
+$countytitle = $county['rdf:RDF']['rdf:Description'][0]['skos:prefLabel']['value'];
+$countycode = $county['rdf:RDF']['rdf:Description'][0]['skos:notation']['value'];
+}
+
+$district = get_xml("http://statistics.data.gov.uk/doc/local-authority/". $row['county'] . $row['district'] .".rdf");
+$districttitle = $district['rdf:RDF']['rdf:Description'][0]['skos:prefLabel']['value'];
+$districtcode = $district['rdf:RDF']['rdf:Description'][0]['skos:notation']['value'];
+
+$ward = get_xml("http://statistics.data.gov.uk/doc/electoral-ward/". $row['county'] . $row['district'] . $row['ward'] .".rdf");
+$wardtitle = $ward['rdf:RDF']['rdf:Description'][0]['rdfs:label'][1]['value'];
+
+if ($_GET['format'] == "xml") {
+ header ("content-type: text/xml");
+ include("xml.php");
+} elseif ($_GET['format'] == "json") {
+ header('Content-type: application/json');
+ include("json.php");
+} elseif ($_GET['format'] == "rdf") {
+ header ("Content-type: application/rdf+xml");
+ include("rdf.php");
+} elseif ($_GET['format'] == "csv") {
+ header("Content-type: application/octet-stream");
+ include("csv.php");
+} elseif (strlen($_GET['format']) == 0) {
+ header ("content-type: text/html");
+ include("result.php");
+}
+
+}
+?>
BIN postcodes.sql.gz
Binary file not shown.
49 rdf.php
@@ -0,0 +1,49 @@
+<?php
+if ($single) {
+$row['postcode'] = str_replace(" ", "", $row['postcode']);
+?>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:spatialrelations="http://data.ordnancesurvey.co.uk/ontology/spatialrelations/" xmlns:admingeo="http://statistics.data.gov.uk/def/administrative-geography/" xmlns:elecgeo="http://statistics.data.gov.uk/def/electoral-geography/" >
+ <rdf:Description rdf:about="http://www.uk-postcodes.com/postcode/<?php echo strtoupper($row['postcode']); ?>">
+ <geo:lat rdf:datatype="http://www.w3.org/2001/XMLSchema#decimal"><?php echo $lat; ?></geo:lat>
+ <geo:long rdf:datatype="http://www.w3.org/2001/XMLSchema#decimal"><?php echo $lng; ?></geo:long>
+ <spatialrelations:easting rdf:datatype="http://www.w3.org/2001/XMLSchema#float"><?php echo $easting; ?></spatialrelations:easting>
+ <spatialrelations:northing rdf:datatype="http://www.w3.org/2001/XMLSchema#float"><?php echo $northing; ?></spatialrelations:northing>
+<?php if ($row['county'] != "00") { ?>
+ <spatialrelations:t_spatiallyInside rdf:resource="http://statistics.data.gov.uk/id/local-authority/<?php echo $row['county']; ?>" />
+<?php } ?>
+ <spatialrelations:t_spatiallyInside rdf:resource="http://statistics.data.gov.uk/id/local-authority/<?php echo $row['county']; ?><?php echo $row['district']; ?>" />
+ <spatialrelations:t_spatiallyInside rdf:resource="http://statistics.data.gov.uk/id/electoral-ward/<?php echo $row['county']; ?><?php echo $row['district']; ?><?php echo $row['ward']; ?>" />
+ <?php if ($row['county'] != "00") { ?>
+ <admingeo:localAuthority rdf:resource="http://statistics.data.gov.uk/id/local-authority/<?php echo $row['county']; ?>" />
+<?php } ?>
+ <admingeo:localAuthority rdf:resource="http://statistics.data.gov.uk/id/local-authority/<?php echo $row['county']; ?><?php echo $row['district']; ?>" />
+ <elecgeo:ward rdf:resource="http://statistics.data.gov.uk/id/electoral-ward/<?php echo $row['county']; ?><?php echo $row['district']; ?><?php echo $row['ward']; ?>" />
+ </rdf:Description>
+ <?php if ($row['county'] != "00") { ?>
+ <rdf:Description rdf:about="http://statistics.data.gov.uk/id/local-authority/<?php echo $row['county']; ?>">
+ <rdfs:label><?php echo $countytitle; ?></rdfs:label>
+ </rdf:Description>
+<?php } ?>
+ <rdf:Description rdf:about="http://statistics.data.gov.uk/id/local-authority/<?php echo $row['county']; ?><?php echo $row['district']; ?>">
+ <rdfs:label><?php echo $districttitle; ?></rdfs:label>
+ </rdf:Description>
+ <rdf:Description rdf:about="http://statistics.data.gov.uk/id/electoral-ward/<?php echo $row['county']; ?><?php echo $row['district']; ?><?php echo $row['ward']; ?>">
+ <rdfs:label><?php echo $wardtitle; ?></rdfs:label>
+ </rdf:Description>
+</rdf:RDF>
+<?php } elseif ($distance) { ?>
+<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
+ xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
+<?php
+while ($row = mysql_fetch_array($result)) {
+$row['postcode'] = str_replace(" ", "", $row['postcode']);
+?>
+ <rdf:Description rdf:about="http://www.uk-postcodes.com/postcode/<?php echo strtoupper($row['postcode']); ?>">
+ <rdfs:label><?php echo strtoupper($row['postcode']); ?></rdfs:label>
+ <geo:lat rdf:datatype="http://www.w3.org/2001/XMLSchema#decimal"><?php echo $lat; ?></geo:lat>
+ <geo:long rdf:datatype="http://www.w3.org/2001/XMLSchema#decimal"><?php echo $lng; ?></geo:long>
+ </rdf:Description>
+<?php } ?>
+</rdf:RDF>
+<?php } ?>
95 result.php
@@ -0,0 +1,95 @@
+<?php
+if ($single) {
+?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
+<head>
+ <title>UK Postcodes | Data for <?php echo strtoupper($row['postcode']); ?></title>
+ <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/grid.css" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/typography.css" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/forms.css" />
+<link type="text/css" rel="stylesheet" href="/style.css" />
+</head>
+<body>
+<div id="header">
+<h1><a href="http://www.uk-postcodes.com">UK Postcodes</a></h1>
+</div>
+<div id="main" class="vcard">
+<div class="adr">
+<h2>Data for <span class="fn org postal-code"><?php echo strtoupper($row['postcode']); ?></span></h2>
+<div id="wrapper" class="result geo">
+<p><strong>Latitude</strong> <span class="latitude"><?php echo $lat; ?></span></p>
+<p><strong>Longitude</strong> <span class="longitude"><?php echo $lng; ?></span></p>
+<p><strong>Easting</strong> <?php echo $easting; ?></p>
+<p><strong>Northing</strong> <?php echo $northing; ?></p>
+<p><strong>Geohash URI</strong> <a href="<?php echo $geohash; ?>" class="url"><?php echo $geohash; ?></a></p>
+<p><strong>Openly Local URL</strong> <a href="http://openlylocal.com/areas/postcodes/<?php echo $row['postcode']; ?>" rel="tag" class="url">http://openlylocal.com/areas/postcodes/<?php echo $row['postcode']; ?></a></p>
+<?php
+if ($row['county'] != "00") {
+?>
+<p><strong>County</strong> <a href="<?php echo "http://statistics.data.gov.uk/doc/local-authority/". $row['county']; ?>"><?php echo $countytitle; ?></a></p>
+<?php } ?>
+<p><strong>District</strong> <a href="<?php echo "http://statistics.data.gov.uk/doc/local-authority/". $row['county'] . $row['district']; ?>"><?php echo $districttitle; ?></a></p>
+<p><strong>Ward</strong> <a href="<?php echo "http://statistics.data.gov.uk/doc/electoral-ward/". $row['county'] . $row['district'] . $row['ward'];?>" class="locality"><?php echo $wardtitle; ?></a></p>
+</div>
+</div>
+</div>
+<div id="formats">
+<p>Get this information as <a href="http://www.uk-postcodes.com<?php echo $_SERVER['REQUEST_URI']; ?>.xml">XML</a>, <a href="http://www.uk-postcodes.com<?php echo $_SERVER['REQUEST_URI']; ?>.csv">CSV</a>, <a href="http://www.uk-postcodes.com<?php echo $_SERVER['REQUEST_URI']; ?>.json">JSON</a> or <a href="http://www.uk-postcodes.com<?php echo $_SERVER['REQUEST_URI']; ?>.rdf">RDF</a> <img src="http://www.uk-postcodes.com/microformats.png" alt="Microformats" style="float:right; margin-left: 10px;" /> <img src="http://m.okfn.org/images/ok_buttons/od_80x15_blue.png" alt="Open Data" style="float:right;" /></p>
+</div>
+<script type="text/javascript">
+var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
+document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
+</script>
+<script type="text/javascript">
+try {
+var pageTracker = _gat._getTracker("UA-511839-16");
+pageTracker._trackPageview();
+} catch(err) {}</script>
+</body>
+</html>
+<?php } elseif($distance) { ?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
+<head>
+ <title>UK Postcodes | Postcodes within <?php echo $distance; ?> miles of <?php echo $title; ?></title>
+ <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/grid.css" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/typography.css" />
+<link type="text/css" rel="stylesheet" href="http://www.blueprintcss.org/blueprint/src/forms.css" />
+<link type="text/css" rel="stylesheet" href="/style.css" />
+</head>
+<body>
+<div id="header">
+<h1><a href="http://www.uk-postcodes.com">UK Postcodes</a></h1>
+</div>
+<div id="main">
+<h2>Postcodes within <?php echo $distance; ?> miles of <?php echo $title; ?></h2>
+<div id="wrapper" class="result">
+<ul>
+<?php
+while ($row = mysql_fetch_array($result)) {
+?>
+<li><a href="http://www.uk-postcodes.com/postcode/<?php echo str_replace(" ", "", $row['postcode']); ?>"><?php echo $row['postcode']; ?></a></li>
+<?php
+}
+?>
+</ul>
+</div>
+</div>
+<div id="formats">
+<p>Get this information as <a href="http://www.uk-postcodes.com<?php echo $_SERVER['REQUEST_URI']; ?>&amp;format=xml">XML</a>, <a href="http://www.uk-postcodes.com<?php echo $_SERVER['REQUEST_URI']; ?>&amp;format=csv">CSV</a>, <a href="http://www.uk-postcodes.com<?php echo $_SERVER['REQUEST_URI']; ?>&amp;format=json">JSON</a>, <a href="http://www.uk-postcodes.com<?php echo $_SERVER['REQUEST_URI']; ?>&amp;format=rdf">RDF</a> or <a href="http://www.uk-postcodes.com<?php echo $_SERVER['REQUEST_URI']; ?>&amp;format=kml">KML</a> <img src="http://m.okfn.org/images/ok_buttons/od_80x15_blue.png" alt="Open Data" style="float:right;" /></p>
+</div>
+<script type="text/javascript">
+var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
+document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
+</script>
+<script type="text/javascript">
+try {
+var pageTracker = _gat._getTracker("UA-511839-16");
+pageTracker._trackPageview();
+} catch(err) {}</script>
+</body>
+</html>
+<?php } ?>
47 xml.php
@@ -0,0 +1,47 @@
+<?php
+if ($single) {
+?>
+<result>
+ <postcode><?php echo $row['postcode']; ?></postcode>
+ <geo>
+ <lat><?php echo $lat; ?></lat>
+ <lng><?php echo $lng; ?></lng>
+ <easting><?php echo $easting; ?></easting>
+ <northing><?php echo $northing; ?></northing>
+ <geohash><?php echo $geohash; ?></geohash>
+ </geo>
+ <administrative>
+<?php
+if ($row['county'] != "00") {
+?>
+ <county>
+ <title><?php echo $countytitle; ?></title>
+ <uri>http://statistics.data.gov.uk/id/local-authority/<?php echo $row['county']; ?></uri>
+ </county>
+<?php } ?>
+ <district>
+ <title><?php echo $districttitle; ?></title>
+ <uri>http://statistics.data.gov.uk/id/local-authority/<?php echo $row['county'] . $row['district']; ?></uri>
+ </district>
+ <ward>
+ <title><?php echo $wardtitle; ?></title>
+ <uri>http://statistics.data.gov.uk/id/electoral-ward/<?php echo $row['county'] . $row['district'] . $row['ward']; ?></uri>
+ </ward>
+ </administrative>
+</result>
+<?php } elseif($distance) { ?>
+<result>
+ <postcodes>
+<?php
+while ($row = mysql_fetch_array($result)) {
+?>
+ <postcode>
+ <lat><?php echo $row['lat']; ?></lat>
+ <lng><?php echo $row['lng']; ?></lng>
+ <distance><?php echo $row['distance']; ?></distance>
+ <uri>http://www.uk-postcodes.com/postcode/<?php echo str_replace(" ", "", $row['postcode']); ?></uri>
+ </postcode>
+<?php } ?>
+ </postcodes>
+</result>
+<?php } ?>
106 xmlparse.php
@@ -0,0 +1,106 @@
+<?php
+
+// Two Custom functions to parse XML from external feeds. The first one is used to return an associative array from an XML document, and the second one gets the data via CURL and returns the array. The rest is up to you!!
+
+function xml2array($contents, $get_attributes=1) {
+ if(!$contents) return array();
+
+ if(!function_exists('xml_parser_create')) {
+ //print "'xml_parser_create()' function not found!";
+ return array();
+ }
+ //Get the XML parser of PHP - PHP must have this module for the parser to work
+ $parser = xml_parser_create();
+ xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
+ xml_parser_set_option( $parser, XML_OPTION_SKIP_WHITE, 1 );
+ xml_parse_into_struct( $parser, $contents, $xml_values );
+ xml_parser_free( $parser );
+
+ if(!$xml_values) return;//Hmm...
+
+ //Initializations
+ $xml_array = array();
+ $parents = array();
+ $opened_tags = array();
+ $arr = array();
+
+ $current = &$xml_array;
+
+ //Go through the tags.
+ foreach($xml_values as $data) {
+ unset($attributes,$value);//Remove existing values, or there will be trouble
+
+ //This command will extract these variables into the foreach scope
+ // tag(string), type(string), level(int), attributes(array).
+ extract($data);//We could use the array by itself, but this cooler.
+
+ $result = '';
+ if($get_attributes) {//The second argument of the function decides this.
+ $result = array();
+ if(isset($value)) $result['value'] = $value;
+
+ //Set the attributes too.
+ if(isset($attributes)) {
+ foreach($attributes as $attr => $val) {
+ if($get_attributes == 1) $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
+ /** :TODO: should we change the key name to '_attr'? Someone may use the tagname 'attr'. Same goes for 'value' too */
+ }
+ }
+ } elseif(isset($value)) {
+ $result = $value;
+ }
+
+ //See tag status and do the needed.
+ if($type == "open") {//The starting of the tag '<tag>'
+ $parent[$level-1] = &$current;
+
+ if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
+ $current[$tag] = $result;
+ $current = &$current[$tag];
+
+ } else { //There was another element with the same tag name
+ if(isset($current[$tag][0])) {
+ array_push($current[$tag], $result);
+ } else {
+ $current[$tag] = array($current[$tag],$result);
+ }
+ $last = count($current[$tag]) - 1;
+ $current = &$current[$tag][$last];
+ }
+
+ } elseif($type == "complete") { //Tags that ends in 1 line '<tag />'
+ //See if the key is already taken.
+ if(!isset($current[$tag])) { //New Key
+ $current[$tag] = $result;
+
+ } else { //If taken, put all things inside a list(array)
+ if((is_array($current[$tag]) and $get_attributes == 0)//If it is already an array...
+ or (isset($current[$tag][0]) and is_array($current[$tag][0]) and $get_attributes == 1)) {
+ array_push($current[$tag],$result); // ...push the new element into that array.
+ } else { //If it is not an array...
+ $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
+ }
+ }
+
+ } elseif($type == 'close') { //End of tag '</tag>'
+ $current = &$parent[$level-1];
+ }
+ }
+
+ return($xml_array);
+}
+
+function get_xml($url) {
+$ch = curl_init($url);
+
+curl_setopt($ch, curlOPT_HEADER, 0);
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+
+$data = curl_exec($ch);
+
+curl_close($ch);
+
+$news = xml2array($data);
+return $news;
+}
+?>

0 comments on commit 4dacc45

Please sign in to comment.
Something went wrong with that request. Please try again.