繁体   English   中英

通过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) { } 

我的代码有什么问题?

在构建GET / POST / REQUEST超全局变量时,PHP期望提交的数据中包含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'));

您将在此处找到更多信息: 如何在php中获取POST正文?

暂无
暂无

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

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