问题描述
我必须做一个API
.为此,我将使用POST以JSON
的形式从移动设备接收数据.我必须处理这些数据,并将响应也以JSON
的形式发送回设备.但是我不知道如何获取将要接收的数据.我尝试使用CURL
进行一些测试,以查看如何获取此数据,但$_POST
始终为空.能否请您告诉我如何使用CURL
将数据以JSON
格式发送到API,以及如何接收此数据,以便可以使用它并将其作为响应发送回去?
I have to make an API
. For this, I will receive the data from the mobile devices as JSON
using POST. I have to work with this data and send the response back to the devices also as JSON
.But I don't know how to take the data that I will receive. I have tried to make some tests using CURL
to see how can I take this data but the $_POST
is always empty. Can you please tell me how to send the data as JSON
format to the API using CURL
and how can I receive this data so I can work with it and send it back as response?
这些是我的测试文件:
curl.php:
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);
test.php:
test.php:
var_dump($_POST);
我得到的答复是:
array(0) { }
推荐答案
您需要将POST数据作为URL查询字符串或数组传递,问题是您以JSON格式发布数据,但PHP无法解析JSON自动,因此$_POST
数组为空.如果需要,您需要在test.php中自己解析:
You need to pass the POST data as a URL query string or as an array, the problem is you post data in JSON format, but PHP does not parse JSON automatically, so the $_POST
array is empty. If you want it, you need do the parsing yourself in the test.php:
$raw_post = file_get_contents("php://input");
$data = json_decode($raw_post, true);
print_r($data);
这篇关于如何使用CURL向API发送数据或从API接收数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!