我的代码是
$urltopost = "http://example.com/webservice/service.php";
$datatopost = array (0 =>array('a'=>'b','c'=>'d'),1 =>array('a'=>'b','c'=>'d'),2 =>array('a'=>'b','c'=>'d'),3 =>array('a'=>'b','c'=>'d'));
$ch = curl_init ($urltopost);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, json_encode($datatopost));
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$returndata = curl_exec ($ch);
我没有把这个json送到我的网址......
答案 0 :(得分:0)
尝试这样的事情:(将你的json字符串长度放入内容长度)
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$ch = curl_init('http://api.local/rest/users');
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))
);
$result = curl_exec($ch);
答案 1 :(得分:0)
您正尝试在service.php
上发布原始JSON数据。
传递原始JSON数据不会填充$_POST
数组。在service.php
页面上,您需要从php stdin 流中捕获传递的数据,如下所示:
$fp = fopen("php://input", "r");
$data = stream_get_contents($fp);
$decoded_json_data = json_decode($data);
var_dump($decoded_json_data);
还有另一种方法可以让你填充$_POST
数组:
$urltopost = "http://example.com/webservice/service.php";
$datatopost = array (0 =>array('a'=>'b','c'=>'d'),1 =>array('a'=>'b','c'=>'d'),2 =>array('a'=>'b','c'=>'d'),3 =>array('a'=>'b','c'=>'d'));
$data_string = http_build_query(['json' => json_encode($datatopost)]);
$ch = curl_init($urltopost);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.strlen($data_string)]);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$returndata = curl_exec($ch);
现在,在service.php
页面上,您可以通过以下方式访问多维数组:
if (isset($_POST['json'])){
$data = json_decode($_POST['json']);
}
答案 2 :(得分:0)
终于得到了解决方案。它正在使用多维数组。
$urltopost = "http://example.com/webservice/service.php";
$datatopost = array (0 =>array('a'=>'b','c'=>'d'),1 =>array('a'=>'b','c'=>'d'),2 =>array('a'=>'b','c'=>'d'),3 =>array('a'=>'b','c'=>'d'));
$post_data = array('data' => serialize($datatopost));
$ch = curl_init ($urltopost);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS,$post_data);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$returndata = curl_exec ($ch);
echo "<pre>";
print_r(unserialize($returndata));
service.php代码
$temp = unserialize($_POST['data']);
echo serialize($temp);