0

Hope you are doing really great. I want to pass the multi-dimential as raw-data to my cURL request. But When I try to pass the array to CURLOPT_POSTFIELDS it gives me an error for Array to String Conversion.

When I am trying to pass the array like:

    $post_data = [
        "date"=> $_POST['date'],
        "items" => $plan_details,
        "form" => [
            "clientName" => [
                "name"      => $_POST['form_data'][0]['clientName'],
                "mobile"    => $_POST['form_data'][0]['mobile'],
            ],
            "clientAddress" => [
                "line"      => $_POST['form_data'][0]['addressLine'],
                "city"      => $_POST['form_data'][0]['addressCity'],
                "state"     => $_POST['form_data'][0]['addressState'],
                "country"   => "",
                "pincode"   => ""
            ],
            "clientGST" => [
                "companyName"   => "",
                "gstNo"         => ""
            ],
        ]
    ];

And the cURL request:

    curl_setopt_array($curl, array(
      CURLOPT_URL => "<URL>",
      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     => $post_data,
      CURLOPT_HTTPHEADER     => array(
            "Authorization: Bearer <key>"
        ),
    ));

How can I pass the Multi-Dimential Array to CURLOPT_POSTFIELDS?

4
  • what POST formats does the target API support? does it support multipart/form-data ? does it support x-www-form-urlencoded ? does it support application/json ? Commented Oct 18, 2021 at 12:23
  • Thank you @hanshenrik. The catch was Content-Type: application/json. I have kept it in CURLOPT_HTTPHEADER and it works fine now. Commented Oct 19, 2021 at 4:54
  • the code you provided above won't work with an API requiring application/json, you would need CURLOPT_POSTFIELDS => json_encode($post_data), for that Commented Oct 19, 2021 at 5:31
  • Correct. I just forgot to mention that. We need to json_encode the data and then provide the Content-type. Commented Oct 19, 2021 at 5:36

1 Answer 1

1

You can use http_build_query function to build postfields string.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help @pavel-třupek but the API server was not accepting the string we built with the http_build_query so the passing of the Content-type in headers worked for me.
I thought you want to encode array into post data parameters, not json encoded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.