2016-06-22 37 views
1

我目前正在使用谷歌地圖API的地理編碼PHP功能。奇怪的是,我想,file_get_contents()返回bool(false),而我使用的url是正確編碼的。php file_get_contents()返回false與一個有效的網址

在我的瀏覽器中,當我測試代碼時,頁面需要很長時間才能加載,並且地理編碼不起作用(當然,考慮到API不給我想要的東西)。

此外,我試圖使用捲曲,迄今沒有成功。

如果有人能幫助我,那會很棒!

非常感謝。

代碼:

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:這個問題確實是事實,我是在一個代理。我測試了另一個網絡,它正常工作。 但是,您對我返回的內容以及我如何測試成功的回答也非常好,並且可以幫助我改進代碼。

非常感謝!

+1

最有可能使用的是互聯網的一些代理。 http://stackoverflow.com/questions/5211887/how-to-use-curl-via-a-proxy – Ali

+0

你永遠不會在'gc_geocode()'函數中返回'false'以外的任何東西......你'echo'其他的東西,但從來沒有返回'true' – Ben

+1

嘗試'if(gc_geocode($ addr)=== false)' –

回答

1

問題是的事實,我使用的是代理 。代碼是正確的。

要檢查您與Internet之間是否存在代理,您必須知道網絡的基礎結構。如果您在學校或公司網絡工作,很可能會使用代理來保護本地網絡。 如果您不知道答案,請撥打詢問您的網絡管理員

如果您的網絡中沒有聲明的代理服務器,則仍然有可能存在透明代理服務器。然而,作爲國家接受的回答這個問題:https://superuser.com/questions/505772/how-can-i-find-out-if-there-is-a-proxy-between-myself-and-the-internet-if-there

如果它是一個透明的代理,你將無法在客戶端PC上檢測到它。

某些網站還提供了一些代理檢測器,但我不知道在那裏給出的信息有多相關。這裏有兩個例子:

http://amibehindaproxy.com/

http://www.proxyserverprivacy.com/free-proxy-detector.shtml

1

看看在if聲明:

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

這意味着,如果gc_geocode($addr)返回或者falsenull,該語句將回聲「假」。

但是,你從來沒有真正從函數返回任何東西,所以成功,它返回null

$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($lati && $longi){ 
     echo "(" . $lati . ", " . $longi . ")"; //ECHO isn't RETURN 
     /* You should return something here, e.g. return true */ 
    } else { 
     echo "data not complete <br/>"; 
     return false; 
    } 
} else { 
    echo "status not ok <br/>"; 
    return false; 
} 

或者,你可以改變的if聲明只火當函數返回false

if(gc_geocode($addr)===false){ 
    //... 
1

當你沒有返回任何函數返回null
只需使用:

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

或者:

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

以上功能gc_geocode()我的系統上正常工作,沒有任何多餘的負擔。你還叫gc_geocode()返回你緯度,經度這是正確的,現在你已經檢查過

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

使用

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