【发布时间】:2014-11-02 11:24:59
【问题描述】:
我必须创建一个API。为此,我将使用 POST 以 JSON 的形式从移动设备接收数据。我必须处理这些数据并将响应也以JSON 发送回设备。
但我不知道如何获取我将收到的数据。我尝试使用CURL 进行一些测试以查看如何获取这些数据,但$_POST 始终为空。您能否告诉我如何使用CURL 将数据以JSON 格式发送到API,以及如何接收这些数据以便我可以使用它并将其作为响应发送回来?
这些是我的测试文件:
curl.php:
//set POST variables
$url = 'http://test.dev/test.php';
$data = array(
'fname' => 'Test',
'lname' => 'TestL',
'test' => array(
'first' => 'TestFirst',
'second' => 'TestSecond'
)
);
//open connection
$ch = curl_init($url);
$json_data = json_encode($data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
// execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
测试.php:
var_dump($_POST);
我得到的回应是:
array(0) { }
【问题讨论】:
-
file_get_contents('php://') 从请求正文中获取 json 值
-
我曾尝试使用 file_get_contents 但出现以下错误: file_get_contents(): Invalid php:// URL specified in... file_get_contents(php://): failed to open stream: operation失败...
-
file_get_contents('php://') 将获取提交到您页面的 json 数据...我认为您错过了单引号