Reputation: 154
I am trying to extract one bit of data from a JSON array when loaded with CURL. Its loads it fine from what I can tell if I echo the results but when I to get the postal_town I just keep coming across a blank???? My PHP code :
$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=52.406822,-1.519693&sensor=true";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response, true);
$town = $response_a['results'][0]['address_components'][0]['types']['postal_town'];
echo $town;
And a sample of the JSON result is:
{
"results" : [
{
"address_components" : [
{
"long_name" : "Ringway Rudge",
"short_name" : "A4053",
"types" : [ "route" ]
},
{
"long_name" : "Coventry",
"short_name" : "Coventry",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Coventry",
"short_name" : "Coventry",
"types" : [ "postal_town" ]
},
{
"long_name" : "West Midlands",
"short_name" : "West Midlands",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "England",
"short_name" : "England",
"types" : [ "administrative_area_level_1", "political" ]
},
Upvotes: 0
Views: 44
Reputation: 154
This does the trick, did what Devon said to do, thanks
$result = @file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=53.406822,-1.519693&sensor=true" );
if ($result === FALSE) {
//manage exception from file_get_contents call
} else {
$geocodedinfo = json_decode($result);
if ($geocodedinfo->status == "OK") {
$town = "";
foreach ($geocodedinfo->results[0]->address_components as $addrcomps) {
if ( $addrcomps->types[0] == 'postal_town')
$town = $addrcomps->long_name;
}
}
}
echo $town;
Upvotes: 1