hi,
new to php.
i have just started a project for entering 2 postcodes (zip code) and working the distance between the 2.
if i have to a url like "https://api.postcodes.io/postcodes/cf634px" and when you put that in a browser content is returned within.
how would i use php to echo the result on screen so i can take a set of coordinated

cheers
dave

Recommended Answers

All 4 Replies

i found the answer and am using this

$url = "https://api.postcodes.io/postcodes/cf634px";

$opts = array('http' =>
    array(
        'method' => 'GET',
        'max_redirects' => '0',
        'ignore_errors' => '1'
    )
);

$context = stream_context_create($opts);
$stream = fopen($url, 'r', false, $context);

it displays 1 line like this "string '{"status":200,"result":{"postcode":"CF63 4PX","quality":1,"eastings"........"
how can i format the resultmaybe <br> after ,

dave

Member Avatar for diafol

Make a request with two postcodes, get the eastings and northings of both.
Use the pythagorean method to calculate the straight-line distance between the two coordinates - e.g.

$distanceKm = sqrt( pow($northing1-$northing2,2) + pow($easting1 - $easting2, 2) ) / 1000;
$distanceMiles = $distanceKm / 1.6093;

Then:

echo "Straight-line distance between $postcode1 and $postcode2 is $distanceKm km ($distanceMiles miles)";

The great circle method will give a more accurate calculation over greater distances (due to curve of earth), but for distances less than a 1000 miles, the difference between the two methods is relatively small - probably less than 1%.

Also have a look at here: https://developers.google.com/maps/documentation/distancematrix/intro - it can calculate 'real' distances by road.

But all roads lead to sunny Barry ;)

thanks for that, but how do i take the eastings & northings from the returned string

Member Avatar for diafol

Ok to use an API, you can call for data in a number of ways, depending on your server settings - possibly controlled by your host.

cURL - should work regardless, but I find file_get_contents() (or some equivalents) to be much easier to handle:

$myPostCode = 'cf634px';

$json = file_get_contents("https://api.postcodes.io/postcodes/$myPostCode");

$data = json_decode($json); 

//All the data should now be here in the $data array
print_r($data);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.