JSON Response PHP Problem

Hey guys,

I’m having an issue with the API JSON response at present. I can hit the API endpoint and a response is returned, but beyond that nothing works. When I try to decode that any attempts to read the object/array returns nothing.

Here’s my code (mostly taken from the example):

$link = "https://api.lifx.com/v1/lights/id:d073d50395f7";  
$authToken = "xxx";
$ch = curl_init($link);
$headers = array('Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);

$response is:

[{"id":"d073d50395f7","uuid":"02a0e18c-8512-413b-a80d-278892797049","label":"Bedroom","connected":false,"power":"on","color":{"hue":0.0,"saturation":0.0,"kelvin":3500},"brightness":1.0,"group":{"id":"7378a9c5e8577085ae7ea66c28efd4dc","name":"My Room"},"location":{"id":"a198da09c4cd960a7756063707602672","name":"My Home"},"product":{"name":"Original 1000","identifier":"lifx_original_a21","company":"LIFX","capabilities":{"has_color":true,"has_variable_color_temp":true}},"last_seen":"2016-09-18T04:31:25.000+01:00","seconds_since_seen":36665.582616875}]

Then decode:

$json = json_decode($response);

From this point, any attempt to read values from $json fails. print_r just returns 1.

Any ideas what’s going wrong? I’ve tried this on two separate servers, different PHP versions and nothing works :frowning:

I have hit this issue a couple of times. It’s a very simple solution:

$json = json_decode($response, true);

Including that ‘true’ forces the resulting array to be associative (or something) so that you can access the elements using their names.

1 Like

Ended up getting this working last night with help from Reddit.

Turns out curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

was missing from the code. Once that was added in I was able to work from there. Thanks all!

1 Like