Search code examples
phpgeocodingfile-get-contentsgoogle-geocoding-api

Google Geocoding API only works for one word address


Google geocoding api is working fantastically if I use only one word like

Sydney

But if I use:

Sydney, Australia

It doesn't work it says:

Warning: file_get_contents(https://maps.google.com/maps/api/geocode/json?address=sydney, Australia&sensor=false): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

Even though it works in my browser when I paste this url but when I use this function file_get_contents it doesn't.

My question is simple why it works in my browser when I paste this result and why it doesn't work with the code below. And of course how to fix this.

$a = file_get_contents("https://maps.google.com/maps/api/geocode/json?address=sydney, Australia&sensor=false");

Solution

  • You have to url encode the address:

    $a = file_get_contents("https://maps.google.com/maps/api/geocode/json?address=" . urlencode('sydney, Australia') . "&sensor=false");