PHP:file_get_contents('php://input')返回JSON消息的字符串 [英] PHP: file_get_contents('php://input') returning string for JSON message
问题描述
我正在尝试在我的PHP应用程序中读取JSON消息,这是我的php代码:
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"
}
这是请求标头:
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,
但是,如果我改为回显$json
变量,则会得到以下信息:
However, if I instead echo out the $json
variable I get the following:
S3URL=http%3A%2F%2Furl.com
因此,看起来file_get_contents('php://input');
是以字符串形式而不是以JSON形式读取它,这将使解析变得更加困难.
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.
有什么主意为什么不将其作为JSON返回,或者如何将其作为JSON返回?
Any idea why it isn't being returned as JSON, or how I can get it to be returned as JSON?
推荐答案
您对json_decode
的使用正在创建关联数组,而不是对象.您可以将其视为数组而不是对象.如果您想要一个对象,请改用它:
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);
请参阅文档有关json_decode()
的第二个参数:
关联 如果为TRUE,则返回的对象将转换为关联数组.
assoc When TRUE, returned objects will be converted into associative arrays.
此外,正如Johannes H.在评论中指出的那样,echo $json;
的输出首先表明您实际上并没有接收到JSON,因此您也需要解决该问题.您问为什么不是JSON?没有看到您如何请求此脚本,就无法确定地说.
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.
这篇关于PHP:file_get_contents('php://input')返回JSON消息的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!