Melody Melody - 1 year ago 102
JSON Question

Error getting a json response from http request

I am trying to get the response from an http request from the Hunter API.

The url is something like this :

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


And the response is something like this :

{
"data": {
"email": "[email protected]",
"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
}
}
}


Here is what I am doing in my controller :

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


And here is what json_encode($datas) returns :

{"headers":{}}


I precise that I am working with Symfony3 and testing on my OVH serveur (Performance offer).

Any idea where does come from this response ? and why I am not getting the real response ? Thanks !

Answer Source

As per my comment,

Instead of using CURL (Which is a much harder system to deal with IMO), you should use file_get_contents() like so:

$json = file_get_contents($url);
$obj = json_decode($json,true);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download