简体   繁体   English

将JSON作为请求正文发送或将POST JSON发送到变量中

[英]Send json as request body or POST json in a variable

I am trying to figure out, is there any way of sending raw json to php instead of POST parameter. 我试图弄清楚,有什么方法可以将原始json发送到php而不是POST参数。 If it is possible then which way is best i mean either request body or POST parameter. 如果有可能,那么最好的方法是请求正文或POST参数。

Send an HTTP request which has a JSON string as its request body (here: using curl on the command line): 发送以JSON字符串作为其请求正文的HTTP请求(此处:在命令行上使用curl ):

$ curl -d '{"foo":"bar"}' example.com/test.php

Read this request body in PHP: 阅读PHP中的此请求正文:

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

Decode it: 解码:

$data = json_decode($json, true);

PHP's $_POST superglobal is automatically populated as an array if the request body of a POST request contains URL encoded key-value pairs (eg foo=bar&baz=42 ). 如果POST请求的请求主体包含URL编码的键值对 (例如foo=bar&baz=42 ),则PHP的$_POST超全局变量将自动填充为数组。 In the above example you're still using an HTTP POST request with "POST data". 在上面的示例中,您仍在使用带有“ POST数据”的HTTP POST请求。 It just doesn't automatically end up in $_POST because PHP doesn't know how to decode JSON automagically. 它只是不会自动以$_POST结尾,因为PHP不知道如何自动解码JSON。

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

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