我已经使用了这两种方式在php中调用地理编码api,这是两种方式,
我的解决方案 1,
$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&sensor=false&key=".$google_api_key;
$resp_json = file_get_contents($url);
现在解决方案 2,正在使用 curl,
// google map geocode api url
$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&sensor=false&key=".$google_api_key;
$resp_json = get_web_page($url);
// method
function get_web_page( $url, $cookiesIn = '' ){
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, //return headers in addition to content
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLINFO_HEADER_OUT => true,
CURLOPT_SSL_VERIFYPEER => false, // Validate SSL Cert
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_COOKIE => $cookiesIn
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$rough_content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header_content = substr($rough_content, 0, $header['header_size']);
$body_content = trim(str_replace($header_content, '', $rough_content));
$pattern = "#Set-Cookie:\s+(?<cookie>[^=]+=[^;]+)#m";
preg_match_all($pattern, $header_content, $matches);
$cookiesOut = implode("; ", $matches['cookie']);
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['headers'] = $header_content;
$header['content'] = $body_content;
$header['cookies'] = $cookiesOut;
if($errmsg != ''){
echo json_encode(" ERROR ". $errmsg);
}
return $body_content;
}
现在我的问题是,这两种解决方案都适用于本地系统和我的 Linux 服务器。 但同样的事情在另一台生产服务器上不起作用。
这是我的两个解决方案的错误,
解决方案 1 上的错误,
file_get_contents((: php_network_getaddresses:getaddrinfo 失败:名称或服务未知
和解决方案 2 上的错误,
无法解析主机:maps.googleapis.com;名称或服务未知
我的谷歌密钥很好,在我这边工作。我不确定我与cpanel有什么关系。
不要使用 cURL 方法,请使用file_get_contents()
方法。确保生产服务器也允许使用 API 密钥,因为问题似乎是它不是。除非您的密钥专门设置为通配符,否则它不适用于多个服务器。
http://console.developers.google.com> API 和身份验证> API> 在 Google Maps API 下按更多> 地理编码 API>启用 API 并获取密钥,以便代码类似于