我正在尝试在 php 中开发小的 API 代码,它将使用 PHP curl(从客户端)以 json 格式发送 POST 请求。在接收端(在服务器端),我想解析请求并处理它。但在接收端,它给了我在 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);
?>
Run Code Online (Sandbox Code Playgroud)
在服务器端:
<?php
print_r($_POST);
?>
Run Code Online (Sandbox Code Playgroud)
块引用数组 ( ) 块引用
它总是在服务器端给我空的 POST 数组。我做错了什么还是有另一种方法来解析请求?请指导我。
您可以使用php://input只读流来访问 JSON 发布数据,而不是像这样$_POST
<?php
$json = file_get_contents('php://input');
?>
Run Code Online (Sandbox Code Playgroud)
它将按原样为您提供 POST 数据。稍后您将能够使用 json_decode() 对其进行解码。
示例代码 -
<?php
$json = json_decode(file_get_contents('php://input'));
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3380 次 |
| 最近记录: |