【问题标题】:Error getting a json response from http request从 http 请求获取 json 响应时出错
【发布时间】:2017-07-26 15:33:39
【问题描述】:

我正在尝试从 Hunter API 的 http 请求中获取响应。

网址是这样的:

https://api.hunter.io/v2/email-finder?domain=mydomain&api_key=myapikey&first_name=myfirstname&last_name=myname

响应是这样的:

{
  "data": {
    "email": "emailfound@domain.tld",
    "score": 68,
    "domain": "domain.tld",
    "sources": [
      {
        "domain": "domain.tld",
        "uri": "http://somedomain.tld/",
        "extracted_on": "2017-04-04"
      }
    ]
  },
  "meta": {
    "params": {
      "first_name": "myfirstname",
      "last_name": "mylastname",
      "full_name": null,
      "domain": "domain.tld",
      "company": null
    }
  }
}

这是我在控制器中所做的:

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);

    // return response
    $json = new JsonResponse();
    $datas = $json->setData($response);
    return json_encode($datas);

这是 json_encode($datas) 返回的内容:

{"headers":{}}

我确切地说我正在使用 Symfony3 并在我的 OVH 服务器上进行测试(性能报价)。

知道这个响应来自哪里吗?为什么我没有得到真正的回应?谢谢!

【问题讨论】:

  • 一定要用curl吗?根据我的经验,您可以使用$json = file_get_contents($url); 更轻松地获得 api 结果
  • 它运行良好!非常简单,谢谢!
  • 如果有人帮助了你,你应该通过点击他们答案左侧的复选标记将答案标记为“正确”:)

标签: php json symfony curl


【解决方案1】:

根据我的评论,

您应该使用file_get_contents(),而不是使用 CURL(这是一个更难处理 IMO 的系统):

$json = file_get_contents($url);
$obj = json_decode($json,true);

【讨论】:

    【解决方案2】:

    试试这个:

    $json = file_get_contents('https://api.hunter.io/v2/email-finder?domain=mydomain&api_key=myapikey&first_name=myfirstname&last_name=myname');
    $data = json_encode($json,true)
    var_dump($data);
    

    【讨论】: