php file_get_contents () returns false with a valid URL

advertisements

I'm currently working on a geocoding php function, using google maps API. Strangely, file_get_contents() returns bool(false) whereas the url I use is properly encoded, I think.

In my browser, when I test the code, the page takes a very long time to load, and the geocoding doesn't work (of course, given that the API doesn't give me what I want).

Also I tried to use curl, no success so far.

If anyone could help me, that'd be great !

Thanks a lot.

The code :

function test_geocoding2(){

    $addr = "14 Boulevard Vauban, 26000 Valence";
    if(!gc_geocode($addr)){
        echo "false <br/>";
    }
}

function gc_geocode($address){

    $address = urlencode($address);
    $url = "http://maps.google.com/maps/api/geocode/json?address={$address}";

    $resp_json = file_get_contents($url);

    $resp = json_decode($resp_json, true);

    if($resp['status']=='OK'){
        $lati = $resp['results'][0]['geometry']['location']['lat'];
        $longi = $resp['results'][0]['geometry']['location']['lng'];

        if($lati && $longi){
            echo "(" . $lati . ", " . $longi . ")";
        }else{
            echo "data not complete <br/>";
            return false;
        }

    }else{
        echo "status not ok <br/>";
        return false;
    }
}

UPDATE : The problem was indeed the fact that I was behind a proxy. I tested with another network, and it works properly. However, your answers about what I return and how I test the success are very nice as well, and will help me to improve the code.

Thanks a lot !


When you are not return anything function returns null.
Just use that:

if(!is_null(gc_geocode($addr))) {
    echo "false <br/>";
}

Or:

if(gc_geocode($addr) === false) {
    echo "false <br/>";
}