使用PHP cURL发布JSON数据

时间:2015-01-30 18:53:20

标签: php laravel curl

情况

  • 我想使用php cURL将JSON数据发布到我的网址http://localhost/api_v2/url?key=***

这是我尝试过的

  

POST功能

public function post(){

    $ch = curl_init("http://localhost/api_v2/url?key=***");

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $file_name = 'inventory.csv';
    $file_path = 'C:\\QuickBooks\\'.$file_name;
    $csv= file_get_contents($file_path);
    $utf8_csv = utf8_encode($csv);
    $array = array_map("str_getcsv", explode("\n", $utf8_csv));
    $json = json_encode($array, JSON_PRETTY_PRINT);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($json))                                                                       
    );

    curl_setopt( $ch, CURLOPT_POSTFIELDS, $json ); 

    curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $json));

    $result = curl_exec($ch);

    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if($status == 200){
        echo "Post Successfully!";
    }
}

2 个答案:

答案 0 :(得分:4)

您的错误就在这一行

  

curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $json));

只需将其更改为

即可

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('json' => $json)));

让我知道,它是怎么回事!

答案 1 :(得分:3)

我对laravel不熟悉,

但您不需要添加行

curl_setopt( $ch, CURLOPT_POSTFIELDS, $json );

之前

curl_exec($ch)?