[英]PHP Curl Send JSON Data
我正在关注本教程: https : //lornajane.net/posts/2011/posting-json-data-with-php-curl
我想做的是通过CURL POST JSON数据
$url = "http://localhost/test/test1.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, $data);
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)));
$result = curl_exec($ch);
var_dump($result);
当我发布纯文本数据时,我能够接收到它,但是当我尝试通过JSON时,我将无法接收到它。
这是我的test1.php
test1.php
print_r($_POST);
print_r($_POST);
任何帮助,将不胜感激。 谢谢
通过cURL
POST JSON Data
,必须使用php://input
。 您可以像这样使用它:
// get the raw POST data
$rawData = file_get_contents("php://input");
// this returns null if not valid json
return json_decode($rawData, true); // will return array
php://input
是一个只读流,允许您从请求正文中读取原始数据
PHP超全局$_POST
只能包装以下数据
application/x-www-form-urlencoded
(用于简单表单发布的标准内容类型)或 multipart/form-data-encoded
(主要用于文件上传) 现在的内容将是application/json
(或至少没有上述提到的内容),因此PHP的$_POST
-wrapper不知道如何处理(还)。
JSON数据不在$ _POST中通过。 您需要使用file_get_contents('php://input');
您还需要对其进行json_decode。
$json = json_decode(file_get_contents('php://input'));
var_dump($json);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.