2014-12-05 153 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>'; 
相關問題