iori
iori

Reputation: 3506

Posting JSON Data With PHP cURL

Situation

Here is what I have tried

POST function

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!";
    }
}

Upvotes: 0

Views: 4068

Answers (2)

code-8
code-8

Reputation: 58652

Your error is in this line

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

Just change it to

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

Let me know, how it goes !

Upvotes: 4

Alex
Alex

Reputation: 17289

I am not familiar with laravel,

but don't you need to add line

curl_setopt( $ch, CURLOPT_POSTFIELDS, $json );

before

curl_exec($ch)?

Upvotes: 3

Related Questions