从一台服务器发送 JSON,然后在另一台服务器上接收


Send JSON from one server and receive at another server

您好,我正在从一台服务器传递一个 JSON 数组,比如说 www.example1.com,我想在另一台服务器上接收该数据,比如说 www.example2.com/test.php。我已经使用 cURL 尝试过这个,但我在接收时没有获得该数据。以下是我的代码

发件人处的代码

$send_data = json_encode($myarray);            
$request_url  = 'www.example2.com/test.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'send_data='.$send_data);
$response = curl_exec($curl);
$curl_error = curl_error($curl);
curl_close($curl); 

接收器处的代码

if(isset($_REQUEST['send_data'])){
    $userinfo = json_decode($_REQUEST['send_data'],true);
    print_r($userinfo);
}

如何在接收端获取数据。

试试这个方法。

文件: example1.com/sender.php

$request_url  = 'www.example2.com/test.php';
$curl = curl_init( $request_url );
# Setup request to send json via POST.
$send_data = json_encode($myarray);  
curl_setopt( $curl, CURLOPT_POSTFIELDS, $send_data );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($curl);
curl_close($curl);
# Print response.
echo "<pre>$result</pre>";

在第二页上,您可以使用 file_get_contents("example1.com/sender.php") 捕获传入请求,该请求将包含 POST 的 json。要以更易读的格式查看接收到的数据,请尝试以下操作:

echo '<pre>'.print_r(json_decode(file_get_contents("example1.com/sender.php")),1).'</pre>';

使用以下

文件: example1.com/sender.php

<?php
header('Content-Type: application/json'); echo
json_encode(array('response1' => 'This is response1', 'response2' => 'This is response2', $_POST));
?>

文件: example2.com/receiver.php

<?php
$request_url  = 'http://www.example1.com/sender.php';
$sendData = array('postVar1' => 'postVar1');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'sendData=' . http_build_query($sendData));
print_r($response = curl_exec($curl));
curl_close($curl);
?>

您将获得一个 JSON 对象作为 cURL 响应。