PHP Curl发送JSON数据
我将学习本教程: 我试图通过CURL发布JSON数据PHP Curl发送JSON数据,php,json,curl,Php,Json,Curl,我将学习本教程: 我试图通过CURL发布JSON数据 $url = "http://localhost/test/test1.php"; $data = array("name" => "Hagrid", "age" => "36"); $data_string = json_encode($data);
$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
发布JSON数据时,您必须使用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超全局$\u POST
,只应包装
(简单表单帖子的标准内容类型)或application/x-www-form-urlencoded
(主要用于文件上传)多部分/表单数据编码
application/json
(或者至少没有上述内容),因此PHP的$\u POST
-包装器还不知道如何处理这个问题
通过
cURL
发布JSON数据时,必须使用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超全局$\u POST
,只应包装
(简单表单帖子的标准内容类型)或application/x-www-form-urlencoded
(主要用于文件上传)多部分/表单数据编码
application/json
(或者至少没有上述内容),因此PHP的$\u POST
-包装器还不知道如何处理这个问题
JSON数据无法通过$\u POST传递。您需要使用
文件获取内容('php://input');代码>
您还需要对其进行json_解码
$json = json_decode(file_get_contents('php://input'));
var_dump($json);
JSON数据无法在$u POST中传递。您需要使用文件获取内容('php://input');代码>
您还需要对其进行json_解码
$json = json_decode(file_get_contents('php://input'));
var_dump($json);
这可能是相关的:.die(curl_error())代码>并告诉我们那是什么says@delboy1978uk没有错误,它确实会向页面发送请求,但当我尝试发送json字符串时,test1.php不接受$\u POST。等等,两个文件都在同一台服务器上?为什么要使用HTTP请求?为什么不在test1.php中使用require并在那里使用$result
?这可能是相关的:.die(curl_error())代码>并告诉我们那是什么says@delboy1978uk没有错误,它确实会向页面发送请求,但当我尝试发送json字符串时,test1.php不接受$\u POST。等等,两个文件都在同一台服务器上?为什么要使用HTTP请求?为什么不在test1.php中使用require并在那里使用$result
?