通过 php 和 cURL 发布 JSON 编码数据

Posting JSON encoded data via php & cURL

我无法通过 PHP 和 cURL

发送 JSON 编码数据

我的发件人代码是:

$id = 1;
$txt = "asdsad";
$txt2 = "baszama";
$data = array("id" => "$id", "txt" => "$txt", "txt2" => "$txt2");
$data_string = json_encode($data);
$ch = curl_init('index.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$result = curl_exec($ch);
curl_close($ch);
echo $result;

index.php:

var_dump($_REQUEST);

我收到的数据:

array(0) { } 

我的代码有什么问题?

PHP 在构建 GET/POST/REQUEST 超全局变量时期望提交的数据中有 key=value 对。您正在发送一个没有密钥的裸字符串。没有键,超全局变量中没有数组条目。

尝试

curl_setopt($ch, CURLOPT_POSTFIELDS, "foo=$data_string");

$_REQUEST['foo']

或者,由于您是通过 POST 发送的,您可以使用

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

然后简单地阅读原始文本。

如果您将请求作为 JSON 字符串发送,那么您必须将其作为字符串读取:

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

您可以在此处找到更多信息:How to get body of a POST in php?