2

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!

8
  • 2
    so var_dump($contents) AFTER you do the utf stuff, and then echo json_last_error(); var_dump($results) after the decode attempt. see what really came out. Commented Nov 20, 2015 at 14:44
  • JSON_ERROR_CTRL_CHAR Commented Nov 20, 2015 at 14:46
  • then skip the utf8 encoding. maybe you're double-encoding or something. Commented Nov 20, 2015 at 14:47
  • again error JSON_ERROR_CTRL_CHAR Commented Nov 20, 2015 at 14:48
  • What's the class instantiated in that $connection variable? Please post the entire code snippet including the part where you setup the connection. Just because you see the same output in the browser when you return the response, doesn't necessarily mean it's encoded properly. Commented Nov 20, 2015 at 14:51

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.