PHP: file_get_contents('php://input') returning string for JSON message

匿名 (未验证) 提交于 2019-12-03 01:12:01

问题:

I am trying to read in a JSON message in my PHP app and this is my php code:

$json = file_get_contents('php://input'); $obj = json_decode($json, TRUE); echo $obj->{'S3URL'}; 

When I do this I am getting the following error:

Trying to get property of non-object in setImage.php on line 25 (line 25 is the echo $obj->{'S3URL'}; line) 

This is the request body of the request to the page:

Request Url: http://localhost:8888/setImage.php Request Method: POST Status Code: 200 Params: {    "S3URL": "http://url.com" } 

This is the request headers:

Accept: application/json Content-Type: application/json Connection: keep-alive Origin: chrome-extension: //rest-console-id User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, 

However, if I instead echo out the $json variable I get the following:

S3URL=http%3A%2F%2Furl.com 

So it looks like file_get_contents('php://input'); is reading it in as a string, and not as JSON, which will make parsing it more difficult.

Any idea why it isn't being returned as JSON, or how I can get it to be returned as JSON?

回答1:

Your use of json_decode is creating an associative array, not an object. You can treat it like an array, instead of an object. If you want an object, use this, instead:

$obj = json_decode($json); 

See the documentation on the second parameter to json_decode():

assoc When TRUE, returned objects will be converted into associative arrays.

Also, as Johannes H. pointed out in the comments, the output of echo $json; indicates that you are not actually receiving JSON, in the first place, so you will need to address that, as well. You asked why it isn't JSON; without seeing how you are requesting this script, it's impossible to say for sure.



回答2:

The problem may be form php://input (is a read-only stream that allows you to read raw data from the request body). change some setting from php.ini , try to make "allow_url_fopen" on.



回答3:

$obj = json_decode($json);

Just remove the true



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!