简体   繁体   中英

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:

在此处输入图像描述

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM