2012-09-03 33 views
0

最近,我嘗試使用谷歌的地方API來搜索的地方。起初,它運作良好。然後我發現,當我通過查詢包含空格。反應總是不好的要求。但是,當我直接將查詢放入瀏覽器時,它運行良好。這是我的代碼,任何人都可以幫助我?如何在查詢包含空間時使用google放置api?

$url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=$name&location=$lat,$lng&radius=$raidus&types=restaurant&sensor=false&key=mykey"; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
// Set so curl_exec returns the result instead of outputting it. 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
// Get the response and close the channel. 
$response = curl_exec($ch); 

例如,如果$ name是'restaurant',它就會起作用。但是如果$ name是'餐館食物',它說不好的要求。然而,我把網址放入瀏覽器,它再次運作。我嘗試清理查詢參數,但響應仍然表示不好的請求。我希望有人能幫助我。

+0

urlencode()字符串 – 2012-09-03 07:32:26

回答

2

總是在某處傳遞URL時,應該對其進行編碼。這將取代例如%20等空格。所以你的$名將是= restaurant%20food

不用擔心谷歌,它會自動解碼它。

要麼你可以手動encdode,或者你可以使用函數如下:

$query = urlencode($query); 

希望它可以幫助

+2

如果他做了上面的整個$ url將會失敗,它會編碼他發佈的url而不僅僅是查詢字符串at問題 – 2012-09-03 07:37:01

+0

@Dagon的+1。如您所示編碼整個'$ url'變量會導致請求失敗。 – BenM

+0

是的,我回答太快:)感謝提醒 – Tom

1

正如其他人所說,你需要使用PHP的urlencode()編碼的URL參數:

$url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=". urlencode($name) ."&location=$lat,$lng&radius=$raidus&types=restaurant&sensor=false&key=mykey"; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
// Set so curl_exec returns the result instead of outputting it. 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
// Get the response and close the channel. 
$response = curl_exec($ch); 
相關問題