When posting form data containing multidimensional arrays using CURL, encountering an "Array to string conversion" error is a common problem. This occurs when attempting to set CURLOPT_POSTFIELDS with an array that includes arrays.
Since the Content-Type header must be multipart/form-data to facilitate file transfer, converting the array to a query string or using http_build_query() is not feasible. Additionally, accessing the receiving host's code to serialize and unserialize the array is not an option.
To resolve this issue, a custom function named http_build_query_for_curl can be employed. It recursively iterates through the array, converting it into a format suitable for CURL POST requests. The modified array can then be assigned to $post and passed to curl_setopt(), avoiding the error.
Here's the code for the http_build_query_for_curl function and an example of its usage:
<code class="php">function http_build_query_for_curl( $arrays, &$new = array(), $prefix = null ) { if ( is_object( $arrays ) ) { $arrays = get_object_vars( $arrays ); } foreach ( $arrays AS $key => $value ) { $k = isset( $prefix ) ? $prefix . '[' . $key . ']' : $key; if ( is_array( $value ) OR is_object( $value ) ) { http_build_query_for_curl( $value, $new, $k ); } else { $new[$k] = $value; } } } $arrays = array( 'name' => array( 'first' => array( 'Natali', 'Yura' ) ) ); http_build_query_for_curl( $arrays, $post ); print_r($post);</code>
The above is the detailed content of How to Solve the \'Array to String Conversion\' Error When Sending Multidimensional Arrays in CURL with PHP?. For more information, please follow other related articles on the PHP Chinese website!