Learner-Driver
Learner-Driver

Reputation: 141

PHP & JSON Parsing

I have read a few Q&As on here and additional articles, but cannot get this script to display the relevant values from the JSON return (which are long and lat from this Google Maps call).

<?php

// Address for Google to search
$address = 'London,UK';

// Get the map json data from Google Maps using the $address variable
$googleCall = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $address .'&sensor=false';

$json = file_get_contents($googleCall);
//header("Content-type: application/json");
//echo $json;

echo $json->results->geometry->location->lat;
echo $json->results->geometry->location->lng;
?>   

I am sure I am 99% there, just cannot see where the error is.

Upvotes: 1

Views: 490

Answers (3)

Ali Akbar Azizi
Ali Akbar Azizi

Reputation: 3516

use json_decode here documentation http://php.net/manual/en/function.json-decode.php

<?php

// Address for Google to search
$address = 'London,UK';

// Get the map json data from Google Maps using the $address variable
$googleCall = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $address .'&sensor=false';

$json = file_get_contents($googleCall);

$json = json_decode($json);


echo $json->results[0]->geometry->location->lat;
echo $json->results[0]->geometry->location->lng;
?>   

Upvotes: 0

Fabio
Fabio

Reputation: 23510

You can decode your json as an associative array and the access to all data with scopes

$address = 'London,UK';
$googleCall = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $address .'&sensor=false';

$json = file_get_contents($googleCall);
$array = json_decode($json, true); //note second parameter on true as we need associative array

echo $array['results'][0]['geometry']['location']['lat'] . '<br>';
echo $array['results'][0]['geometry']['location']['lng'];

This will output

51.5112139
-0.1198244

Upvotes: 2

tess3ract
tess3ract

Reputation: 183

try this out:

<?php

// Address for Google to search
$address = 'London,UK';

// Get the map json data from Google Maps using the $address variable
$googleCall = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $address .'&sensor=false';

$json = file_get_contents($googleCall);

$json = json_decode($json);
//header("Content-type: application/json");
//echo $json;

echo $json->results->geometry->location->lat;
echo $json->results->geometry->location->lng;
?>   

Upvotes: 0

Related Questions