netdev
netdev

Reputation: 566

curl format for CURLOPT_POSTFIELDS

I want to send this via curl:

{
  "clientID": "9J8pM7Y…",
  "data": [
    {
      "photoId": 1,

      "success": true
    }
  ]
}

Ι was trying to send it like this:

$body = str_replace('\"','', wp_json_encode( [
        'clientID' => $clientid,
        'data' => ['photoId' => $photoId, 'success' => true]
    ]))

But then it was a json object not an array of json objects as needed. I tried sending it like a string but with no success:

$body ='{"clientID":"'.$clientid.'","data":[{"photoId":'.$photoId.',"success":true}]}';

Here is the whole curl:

curl_setopt_array($curl, array(
        CURLOPT_URL => "http://example.com/js/RDCJS/UpdatePhotos/",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS =>$body,
        CURLOPT_HTTPHEADER => array(
            "Accept: application/json",
            "Content-Type: application/json"
        ),
    ));

Upvotes: 0

Views: 59

Answers (1)

Barmar
Barmar

Reputation: 780879

Add an array around the data value.

$body = wp_json_encode( [
        'clientID' => $clientid,
        'data' => [['photoId' => $photoId, 'success' => true]]
    ]));

Don't remove the " characters, that produces invalid JSON.

Upvotes: 2

Related Questions