从一台服务器发送JSON并在另一台服务器上接收

时间:2014-12-05 06:22:41

标签: php json curl

您好我从一台服务器传递一个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);
}

如何在接收方端获取数据。

2 个答案:

答案 0 :(得分:1)

尝试这种方法。

文件: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”)捕获传入的请求,该文件将包含POSTed json。要以更易读的格式查看收到的数据,请尝试以下操作:

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

答案 1 :(得分:0)

使用以下

文件: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响应。