在PHP中,使用CURL将JSON数据POST到远程服务器,方法如下:
$postData = ['key1' => 'value1', 'key2' => 'value2',];
$postDataString = json_encode($postData);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/path/to/post');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 设置Content-Type和Content-Length
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Content-Length: ' . strlen($postDataString)]);
// 设置需要POST的数据
curl_setopt($ch, CURLOPT_POSTFIELDS, $postDataString);
$result = curl_exec($ch);
curl_close($ch);
远程服务器接收POST过来的数据,方法如下:
$data = file_get_contents('php://input');
Categories: PHP