如何使用curl发布JSON数据?

时间:2014-03-05 08:12:54

标签: php curl

我正在尝试使用curl发送JSON数据,但它没有发布。

$data = array("name" => " Hagrid", "age" => "36");
$content= json_encode($data,true);
$url ='http://www.example.com/webervices/msg.php';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
    array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
print_r($status);
curl_close($curl);
$response = json_decode($json_response, true);    

并在msg.php

print_r($_POST);

但它会打印一个空白数组。

如果有人有任何使用php发布JSON数据的解决方案,那将会很有帮助。

1 个答案:

答案 0 :(得分:0)

msg.php脚本中,您需要执行此操作以获取json内容:

$body = @file_get_contents('php://input');
print $body;