【问题标题】:Couldn't Connect To Host Error with Google Places API and PHP/cURL无法使用 Google Places API 和 PHP/cURL 连接到主机错误
【发布时间】:2012-02-03 08:43:44
【问题描述】:

我正在尝试使用 PHP 和 cURL 从 Google Places API 获取数据,但 cURL 给我一个错误“无法连接到主机”。如果我将 Google Places 请求 URL 粘贴到浏览器中,它可以正常工作。 file_get_contents 也不起作用。这是我的代码:

$ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    //curl_setopt($ch, CURLOPT_POST, 1);
    //curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldString);
    $result = curl_exec ($ch);
    if (curl_errno($ch)) {
            return curl_error($ch);
    } else {
    curl_close($ch);
    }
    return $result;

我请求的 URL 是 https://maps.googleapis.com/maps/api/place/search/json?key=xxx&location=27.916766641249062,-82.08984375&radius=50000&sensor=true&types=bar%7Cnight_club。出于安全考虑,我删除了我的 API 密钥。

【问题讨论】:

  • 我不是 PHP 人,curl 会自动对请求进行 URL 编码吗?
  • 我尝试对请求进行 URL 编码,没有任何改变

标签: php curl google-places-api


【解决方案1】:

我真的很喜欢尽可能使用file_get_contents(),它是如此简单和优雅。

我经常这样做

<?php
$json = (array) json_decode(file_get_contents("https://maps.googleapis.com/maps/api/place/search/json?key=xxx&location=27.916766641249062,-82.08984375&radius=50000&sensor=true&types=bar%7Cnight_club."));

var_dump($json);
?>

那么你应该会看到这样的数组:

array(3) {
  ["html_attributions"]=>
  array(0) {
  }
  ["results"]=>
  array(0) {
  }
  ["status"]=>
  string(14) "REQUEST_DENIED"
}

显然,我没有正确的 API 密钥 :) 希望它有用。

【讨论】:

  • file_get_contents 只是给了我一个空白页并使用 fsockopen,连接超时
猜你喜欢
  • 2013-07-31
  • 1970-01-01
  • 2018-06-21
  • 2011-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-03
相关资源
最近更新 更多