当查询包含空格时,如何使用googleplaceapi


how to use google place api when query contained space?

最近,我尝试使用谷歌位置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是"餐厅食品",它说这是个糟糕的要求。然而,我把url放进浏览器,它又工作了。我试图清除查询参数,但响应仍然显示错误的请求。我希望有人能帮我。

在将URL传递到某个地方时,您应该对其进行编码。这将用%20等替换空格。因此,您的$name将为=restaurant%20food

不用担心谷歌,它会自动解码。

要么你可以手动加密,要么你可以使用这样的功能:

$query = urlencode($query);

希望它能帮助

正如其他人所说,您需要使用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);