2014-12-05 154 views
0

你好,我正在从一台服务器传递一个JSON数组,比如www.example1.com,我想在另一台服务器上接收这个数据,比如www.example2.com/test.php。我已经使用cURL尝试了这一点,但我没有在接收端获取这些数据。位于发件人从一台服务器发送JSON并在另一台服务器上接收

$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

尝试呼应'$ response' – Ghost 2014-12-05 06:23:49

+0

你应该做上述^ – Darren 2014-12-05 06:25:46

+0

回声$回应给我的输出1 – 2014-12-05 06:26:10

回答

0

使用以下

FILE:example1.com/sender.php

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

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

1

试试这个方法。

FILE: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”)赶上传入的请求,其中将包含已发布JSON。为了更可读的格式查看接收到的数据,试试这个:

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