我正在尝试在 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 数组。我做错了什么还是有另一种方法来解析请求?请指导我。