简体   繁体   English

如何读取以json格式从远程服务器发送的$ _POST字段?

[英]How to read a $_POST field sent from remote server in json format?

This is the code for the notification that I receive from the server that my work is complete. 这是我从服务器收到的工作已完成通知的代码。 It returns a $_POST field, say xyx , in JSON format. 它以JSON格式返回$_POST字段,例如xyx I tried various combinations, even wrapping in json_decode , yet it returns NULL . 我尝试了各种组合,甚至包装在json_decode ,但它返回NULL

I also want to access a few values from the POST for further processing into database. 我还想从POST访问一些值,以便进一步处理到数据库中。

<?php
ini_set('display_errors', 'Off');
echo "notification is arriving ...";
sleep(2);

//echo $_POST['message'];
//print_r($_POST,true);

$json = file_get_contents("php://input");
$obj = json_decode($json);
var_dump($obj);  //CHECKING
?>

SAMPLE OUTPUT: 样品输出:

notification is arriving ...NULL 通知到达... NULL

EDIT : AFter var_dump($_POST); 编辑:之后var_dump($ _ POST);

array(2) { ["xyw"]=> string(2262) "{"ok":"ASSEMBLY_COMPLETED","message":"The assembly was successfully completed.","....and the rest of json output . array(2){[“ xyw”] =>字符串(2262)“ {” ok“:” ASSEMBLY_COMPLETED“,” message“:”该程序集已成功完成。“,” ....以及其余json输出。

After var_dump("php://input") 在var_dump(“ php:// input”)之后

string(11) "php://input" .. If I remove quotes..nothing. string(11)“ php:// input” ..如果我删除引号..什么都没有。 Blank page . 空白页 。

The following line: 下一行:

$json = file_get_contents("php://input");

Will return an ARRAY, not a json object. 将返回一个ARRAY,而不是json对象。 Thus, the following line: 因此,以下行:

$obj = json_decode($json);

is trying to decode an array, and it will fail (because the type of $json is Array and not an json object. 正在尝试解码数组,它将失败(因为$ json的类型是Array而不是json对象。

Hope this answers your question. 希望这能回答您的问题。

EDIT 编辑

If you want your script to return a json object, you should use json_encode instead and then echo it. 如果要让脚本返回json对象,则应改用json_encode,然后回显它。

EDIT2 EDIT2

To read, just do as follows: 要阅读,只需执行以下操作:

$json = file_get_contents("php://input");
$myVar1 = $json['xyw'];
echo $myVar1;

EDIT3 EDIT3

I've seen the output you have pasted and I see that it is a json string, you could encode it as follows: 我已经看到您粘贴的输出,并且看到它是一个json字符串,您可以将其编码如下:

$post= file_get_contents("php://input");
$json = json_encode($post['xyw']);

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM