PHP API在POST中获取空JSON请求
我正在尝试用php开发小型API代码,它将使用php curl(从客户端)以json格式发送POST请求。在接收端(服务器端),我想解析请求并处理它。但在接收端,它给了我post字段中的空数组。 下面是我的代码 客户端:PHP API在POST中获取空JSON请求,php,json,api,curl,Php,Json,Api,Curl,我正在尝试用php开发小型API代码,它将使用php curl(从客户端)以json格式发送POST请求。在接收端(服务器端),我想解析请求并处理它。但在接收端,它给了我post字段中的空数组。 下面是我的代码 客户端: <?php $data = array("name" => "Hagrid", "age" => "36");
<?php
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, "xdata=".$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
echo $result = curl_exec($ch);
?>
<?php
print_r($_POST);
?>
在服务器端:
<?php
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, "xdata=".$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
echo $result = curl_exec($ch);
?>
<?php
print_r($_POST);
?>
大宗报价
数组()
大宗报价
它总是在服务器端给我空的POST数组。
我是做错了还是有其他方法来解析请求?
请引导我。您可以使用php://input只读流访问JSON post数据,而不是像这样的$\u post
<?php
$json = file_get_contents('php://input');
?>
它将按原样为您提供POST数据。稍后您将能够使用json_decode()对其进行解码
示例代码-
<?php
$json = json_decode(file_get_contents('php://input'));
?>
您使用
CURLOPT\u HTTPHEADER
标题设置了错误的内容长度。您的整个post字符串是strlen(“xdata=”.$data\u string)
,而您使用的是strlen($data\u string)
此外,您正在使用application/x-www-form-urlencoded
进行发布,但强烈地提到内容类型为application/json
因此,从代码中删除下面的代码块,您应该不会有问题
// Remove it
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
因此,PHP总是在服务器上。PHP从不在客户端上运行。请尝试添加-curl_setopt($ch,CURLOPT_POST,1);/-谢谢Vikesh,它正在工作。但无法从POST获取数据?@Shirish,
$\u POST
是一个关联的变量数组,当在请求中使用application/x-www-form-urlencoded或multipart/form数据作为HTTP内容类型时,通过HTTP POST方法传递给当前脚本。如需参考,请参阅此链接,如果我的答案有帮助,请接受此链接。“application/x-www-form-urlencoded”适用于我的情况。谢谢你的帮助。