Could not open stream: HTTP request failed! HTTP / 1.0 400 Bad Request

This code that I use to find the latitude and longitude of a place:

function coords($address){
    echo $url="http://maps.googleapis.com/maps/api/geocode/json?address=".$address;
    $json = file_get_contents(urlencode($url));
    $data = json_decode($json, TRUE);

    print_r($data['results'][0]['geometry']['location']['lat']);
    print_r($data['results'][0]['geometry']['location']['lng']);
}

However, it always returns this warning:

Could not open stream: HTTP request failed! HTTP / 1.0 error 400

If I use the above code in a simple procedure, it works fine, but not in a function.

Note. I tried a method curl_init()...that gave the same result?

+4
source share
1 answer

Instead of encoding the entire URL, just encode the address part. The following code will work fine

$add='jamshoro phase 2';
$url="http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($add);
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
print_r($data['results'][0]['geometry']['location']['lat']);
print_r($data['results'][0]['geometry']['location']['lng']);
+13
source

All Articles