通过CURL POST JSON数据并抓住它

时间:2012-01-30 09:56:51

标签: php json curl

我正在尝试将json数据作为cURL POST的参数传递。但是,我坚持抓住它并将其保存在db。

cURL文件:

$data = array("name" => "Hagrid", "age" => "36");                                                                    
$data_string = json_encode($data);                                                                                   

$url = 'http://localhost/project/test_curl';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
                                    'Content-Type: application/json')                                                                                           
                                    );                       
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                                                     

$result = curl_exec($ch);  

//based on http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl

test_curl文件:

    $order_info = $_POST; // this seems to not returning anything

    //SAVE TO DB... saving empty...

我错过了什么? Weew ....

2 个答案:

答案 0 :(得分:20)

您将数据作为原始JSON发送到正文中,它不会填充$_POST变量。

您需要做以下两件事之一:

  1. 您可以将内容类型更改为将填充$_POST数组
  2. 的内容类型
  3. 您可以阅读原始数据。
  4. 如果您可以控制通信的两端,我会建议选项二,因为它会将请求主体大小保持在最小,并随着时间的推移节省带宽。 (编辑:我在这里并没有真正强调它将节省的带宽量可以忽略不计,每个请求只有几个字节,这只是一个有效的问题,是非常高的流量环境。但我仍然建议选项二因为这是最干净的方式

    test_curl文件中,执行以下操作:

    $fp = fopen('php://input', 'r');
    $rawData = stream_get_contents($fp);
    
    $postedJson = json_decode($rawData);
    
    var_dump($postedJson);
    

    如果要填充$_POST变量,则需要更改将数据发送到服务器的方式:

    $data = array (
      'name' => 'Hagrid',
      'age' => '36'
    );
    
    $bodyData = array (
      'json' => json_encode($data)
    );
    $bodyStr = http_build_query($bodyData);
    
    $url = 'http://localhost/project/test_curl';
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/x-www-form-urlencoded',
      'Content-Length: '.strlen($bodyStr)
    ));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyStr);
    
    $result = curl_exec($ch);
    

    原始未解码的JSON现在可以在$_POST['json']中使用。

答案 1 :(得分:0)

使用以下php函数以x-www-form-urlencoded格式使用php curl函数发布数据。

<?php
    $bodyData = http_build_query($data); //for x-www-form-urlencoded
?>
相关问题