ketom
ketom

Reputation: 2444

PHP Json decode not work in laravel

I have a C# client, its send a json to my php server.

There is the json string:

{"data":[{"name":"1"}]}

Its a valid json. When i try it in PHP Sandbox its works good

$ad = '{"data":[{"name":"1"}]}';

$contents = utf8_encode($ad ); 
$results = json_decode($contents); 

var_dump($results->data);

But,when i try in laravel 5.1, its not work good.

$response = $connection -> getData();
// return $response; (Its equal : {"data":[{"name":"1"}]}   )
$contents = utf8_encode($response);
$results = json_decode($contents);

dd($results->data); // Error Trying to get property of non-object

I hope someone can help me. Thanks!

Upvotes: 2

Views: 4967

Answers (1)

patricus
patricus

Reputation: 62228

Based on the comments, it looks like the socket_read() in the getData() method is reading 1 character at a time, and then concatenating each NUL terminated character into a response string. json_decoded() is choking on all the extra NUL characters.

You can either update your logic in the getData() method so it is not doing this, or you can run a str_replace on the results:

$response = $connection -> getData();

// get rid of the extra NULs
$response = str_replace(chr(0), '', $response);

$contents = utf8_encode($response);
$results = json_decode($contents);

dd($results->data);

Upvotes: 1

Related Questions