Silver Dragon
Silver Dragon

Reputation: 33

How to get json from cURL with PHP

I'm trying to decode a json obtening by cURL with php like this :

$url = 'https://www.toto.com/api/v1/ads/?apikey=titi&code_postal='.$code_postal.'&type_de_bois='.$type_bois;
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Accept: application/json'
));

$result = curl_exec($cURL);
curl_close($cURL);

var_dump(json_decode($result, true));
echo json_decode($result);

That returns me that, something which seems to be json :

[{"id":"6918","nom":"X","code_postal":"88120","ville":"town","description":"test","logo":"test.png","url":"test","telephone":true}, [{"id":"6919","nom":"Y","code_postal":"88121","ville":"town1","description":"test","logo":"test.png","url":"test","telephone":true}, [{"id":"6920","nom":"Z","code_postal":"88122","ville":"town2","description":"test","logo":"test.png","url":"test","telephone":true}]

int(1) 1

My question are : - Why, without echo or print, the array is printed? - Why json_decode doesn't work propely or why it is only one value ("1")?

Thanks a lot for your answer.

Upvotes: 1

Views: 14789

Answers (2)

Barmar
Barmar

Reputation: 782166

You forgot to use the CURLOPT_RETURNTRANSFER option. So curl_exec() printed the response instead of returning it into $result, and $result just contains the value TRUE that was returned by curl_exec to indicate that it was successful. Add:

curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

Upvotes: 7

medskill
medskill

Reputation: 330

It seems like the json data is encoded two times if after using once json_decode(), the result is a json string.

Please check this :

echo json_decode(json_decode($result));

If it won't work, could you provide the response of

echo $result; 

to see the server response non parsed by PHP.

Upvotes: 0

Related Questions