在php curl中收到json

时间:2014-06-11 07:42:19

标签: php json curl

我尝试使用此代码发送数据并将其转换为json。

$data = array();
$data['firstname']= "sample";
$data['lastname']="sampel lastname";

$post_str = '';

foreach($data as $key => $val){
   $post_str .= $key.'='.urlencode($val).'&';   
}

$post_str = substr($post_str,0,-1);


$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'http://localhost/receive_data_curl.php');

curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Accept: application/json',                                                                         
    'Content-type: application/json')
); 
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$post_str);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER,0);
$response = curl_exec($ch);

curl_close($ch);

我的问题是如何才能收到我通过json发送的数据? 我真的不知道如何获取数据,我脑海中唯一的代码是header()。我在youtube上观看了其他教程但是我失败了。

我尝试使用此代码来获取没有CURLOPT_HTTPHEADER

的数据
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];

$fh = fopen('receice.txt','w');
fwrite($fh,$firstname." = ".$lastname);
fclose($fh);

它确实有效但如果我添加了CURLOPT_HTTPHEADER,它就无法正常工作。

这里是linux命令代码

curl - v 
- H "Accept: application/json" 
- H "Content-type: application/json" 
- X POST 
- d '{"cart" : 
        {"cancel_url":"http://yourdomain.com/your_cancel_url",
        "invoice":"11111111",
        "notes":"sample note",
        "success_url":"http://yourdomain.com/your_success_url",
        "total_amount":"30.0",
    }'

1 个答案:

答案 0 :(得分:0)

您尝试使用以下代码发送数据

$data = array();
$data['firstname']= "sample";
$data['lastname']="sampel lastname";
$send_json_data = json_encode($data);

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'http://localhost/receive_data_curl.php');

curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Accept: application/json',                                                                         
    'Content-type: application/json')
); 
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$send_json_data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER,0);
$response = curl_exec($ch);

curl_close($ch);

接收数据

$json = file_get_contents('php://input');
$json_receive_data = json_decode($json,true);
$firstname = $json_receive_data['firstname'];
$lastname = $json_receive_data['lastname'];

$fh = fopen('receice.txt','w');
fwrite($fh,$firstname." = ".$lastname);
fclose($fh);