我正在尝试使用以下PHP代码向Google Places API发送帖子请求但我收到错误
string(141)" {" error_message" :"此服务需要API密钥。", " html_attributions" :[],"结果" :[],"状态" :" REQUEST_DENIED" }"
<?php
include_once 'configuration.php';
$url = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
$data = array('query' => 'restaurants in Sydney', 'key' => API_KEY);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
问题出在哪里?
答案 0 :(得分:2)
如documentation of text search中所述,参数需要在GET方法中。您以POST方式提供了它。
A Text Search request is an HTTP URL of the following form:
https://maps.googleapis.com/maps/api/place/textsearch/output?parameters
...
Certain parameters are required to initiate a search request. As is standard in URLs, all parameters are separated using the ampersand (&) character.
请尝试使用此代码段:
<?php
include_once 'configuration.php';
$url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=' . urlencode('restaurants in Sydney') . '&key=' . API_KEY;
$result = file_get_contents($url);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
要使用数组参数,请将$url
更改为:
$data = array('query' => 'restaurants in Sydney', 'key' => API_KEY);
$url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?' . http_build_query($data);