Laravel 5.6中用CURL调用POST类型REST API报错求助
Hey there, let's break down why you're seeing that "Array to string conversion" error and how to fix it quickly!
The Root Cause
When you use CURLOPT_POSTFIELDS with an array in cURL, it automatically encodes the data as application/x-www-form-urlencoded (like standard form data). But your API expects JSON-formatted data—exactly what you're sending successfully in Postman. Since your $request->data is a nested array (with Lines and Payments containing their own arrays), cURL tries to force this nested structure into a string, which triggers the conversion error.
The Solution
You need to explicitly convert your data array to a valid JSON string using json_encode(), and ensure your request headers clearly signal that you're sending JSON. Here's the adjusted, working code:
$curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $request->url, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30000, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", // Convert the nested data array to a JSON string CURLOPT_POSTFIELDS => json_encode($request->data), CURLOPT_HTTPHEADER => array( "accept: */*", "accept-language: en-US,en;q=0.8", "content-type: application/json", // Critical: tells the API to expect JSON "Accept: application/json", ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); // Optional: Add error handling and response parsing if ($err) { dd("cURL Error #:" . $err); } else { // Decode the API's JSON response into a PHP array if needed $responseData = json_decode($response, true); dd($responseData); }
Key Checks to Confirm
- Validate
$request->data: Make sure$request->datais a proper PHP array (not a pre-encoded string). You can verify this withdd($request->data)to ensure its structure matches the JSON parameter you provided. - Avoid duplicate headers: Your original code has two
Acceptheaders—while this isn't breaking things, it's cleaner to keep one consistent entry forAccept: application/json.
Your Original JSON Parameter (For Reference)
{ "DebtorID":"00000000080000000002", "InitiatedDate":"2018-04-20", "OrderNo":"1234", "SOReference":"Test order", "Lines":[ {"PartNo":"1170","QuantityOrdered":5}, {"CommentLine":"true","CommentText":"This is a comment line"}, {"InventoryID":"000000000K00000000BV","QuantityOrdered":2, "DiscountedPrice":15.67, "CustomFieldValues":[{"SettingID":"1ae102b94dc54dfc8a45", "Contents":"Fragile - do not drop" } ] } ], "Payments":[{"PaymentRef":"S454873-J5","AmountPaid":50.00}] }
内容的提问来源于stack exchange,提问作者pankaj

