【问题标题】:PHP cURL "Could not resolve host: maps.googleapis.com; Unknown error"PHP cURL“无法解析主机:maps.googleapis.com;未知错误”
【发布时间】:2015-08-28 23:12:07
【问题描述】:

我意识到这个问题之前已经被问过好几次了,但我已经尝试了给出的答案,我感觉,上下感觉就像我的头撞到了墙上。

PHP/cURL:

$this->ch = curl_init();

curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST,  2);

curl_setopt($this->ch, CURLOPT_URL, "https://maps.googleapis.com/maps/api/geocode/json?address=1956+Mountain+View+Drive,+San+Diego,+CA&key=?????");
curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "GET");

$response = curl_exec($this->ch);

var_dump($response);
var_dump(curl_error($this->ch)); die;

按原样,我收到“无法解析主机:maps.googleapis.com;未知错误”。如果我添加这个:

curl_setopt($this->ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 )

在另一篇文章中建议,错误更改为:“无法解析主机:maps.googleapis.com;名称或服务未知”

无论哪种方式,我似乎都找不到不出错的方法。我可以将 URL 放入 Web 浏览器,它对我来说很好地进行地理编码。我们有许多其他 API 集成,它们使用与 cURL 类似的设置并且工作正常,所以我不认为这是一个普遍的服务器范围的问题,但它是特定于这个用例的。

有什么想法吗?

【问题讨论】:

  • 您能否发布指向您尝试过答案的问题的链接?它可以激发某人给出一个对你有用的新答案,或者告诉其他人什么对你没有用。
  • 所有围绕此类问题的 stackoverflow 问题要么是 (1) 服务器相关的(我相信我的问题仅限于这个用例),要么 (2) 围绕关闭验证节点,添加verifyhost 并将其设置为 2,或将 curl_ipresolve 更改为版本 4。我上面的代码试图解决所有这些问题,但事情仍然无法通过 cURL 工作(尽管当我在浏览器窗口中直接键入请求 URL 时它们会起作用)

标签: php curl


【解决方案1】:

在继续之前,您是否已创建地理编码 API? 如果没有转到http://console.developers.google.com > APIs & auth > APIs > 在 Google Maps APIs 下按更多 > Geocoding API > 启用 api 并获取您的密钥 所以代码会像

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);

curl_setopt($ch, CURLOPT_URL, "https://maps.googleapis.com/maps/api/geocode/json?address=1956+Mountain+View+Drive,+San+Diego,+CA&key=YOUR_KEY_HERE");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

$response = curl_exec($ch);

print "<pre>";
var_dump($response);
var_dump(curl_error($ch)); die;

如果上述方法不起作用,那么我假设的 curl 库可能有问题,

除此之外,因为您只请求获取数据,您可以简单地使用

file_get_contents()

<?php
echo file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address=1956+Mountain+View+Drive,+San+Diego,+CA&key=YOUR_KEY");

然后会输出

{ "results" : [ { "address_components" : [ { "long_name" : "1956", "short_name" : "1956", "types" : [ "street_number" ] }, { "long_name" : "North Mountain View Drive", "short_name" : "N Mountain View Dr",...

【讨论】:

  • 抱歉延迟回复。是的,我已经创建了密钥。我可以将整个请求放入浏览器,它对我来说非常适合地理编码。但是当我尝试通过 cURL 运行它时,我遇到了解决主机问题的问题。
  • 确实如此。拧卷曲。谢谢!
猜你喜欢
  • 2019-05-04
  • 1970-01-01
  • 2011-05-20
  • 1970-01-01
  • 2017-10-19
  • 1970-01-01
  • 2019-05-19
  • 1970-01-01
  • 2018-06-21
相关资源
最近更新 更多