Search code examples
phpjsongoogle-geocoder

file get content google geocode not working


When i try to execute the code below, it dont work.

        $json = file_get_contents('https://maps.google.com/maps/api/geocode/json?address=R%20GRANJAO,%2021&sensor=false&key=MYAPIHERE');
        var_dump($json);

The code above return me with "ZERO_RESULTS".

But if i manualy access the link, it returns the contents.

Example below:

enter image description here

Of course i am using a valid API, because most of the addresses work, but a few, just like this example, dont.

I tried to use urlencode() as well, but it doesnt seens to be the problem here.


Solution

  • I seens that it was necessary to add a header setting 'accept-language'.

            $url = "https://maps.google.com/maps/api/geocode/json?address=".urlencode($address)."&sensor=false&key=$apiKey";
            $header = array('Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3');
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            $json = curl_exec($curl);
            $err = curl_error($curl);
            curl_close($curl);
    
            $response = json_decode($json, true);
    

    This solved the issue!