PHP Json解码在laravel不工作

时间:2022-10-26 09:11:44

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

我有一个c#客户端,它向我的php服务器发送一个json。

There is the json string:

json字符串:

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

{“数据”:[{“名称”:“1”}]}

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

一个有效的json。当我在PHP沙箱中尝试时,它的效果很好

$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.

但是,当我尝试laravel 5.1时,它并不是很好用。

$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!

我希望有人能帮助我。谢谢!

1 个解决方案

#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.

根据注释,看起来getData()方法中的socket_read()每次读取一个字符,然后将每个NUL终止字符连接到响应字符串中。json_decoded()将所有额外的NUL字符都填满了。

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:

您可以在getData()方法中更新您的逻辑,因此它不是这样做的,或者您可以在结果中运行str_replace:

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

#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.

根据注释,看起来getData()方法中的socket_read()每次读取一个字符,然后将每个NUL终止字符连接到响应字符串中。json_decoded()将所有额外的NUL字符都填满了。

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:

您可以在getData()方法中更新您的逻辑,因此它不是这样做的,或者您可以在结果中运行str_replace:

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