从http请求获取json响应时出错

时间:2017-07-26 15:33:39

标签: php json symfony curl

我正在尝试从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服务器上进行测试(性能提供)。

知道这个回复的来源吗?为什么我没有得到真正的回应?谢谢!

2 个答案:

答案 0 :(得分:1)

根据我的评论,

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

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

答案 1 :(得分:0)

试试这个:

$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);