Home >Backend Development >PHP Tutorial >How to Post Multidimensional Arrays via PHP and CURL?
Problem:
Posting a multidimensional form array via CURL to a PHP script on a different host results in an "Array to string conversion" error. The third argument of curl_setopt() must be an array to set the Content-Type header to multipart/form-data due to file upload. However, it seems that CURLOPT_POSTFIELDS does not support multidimensional arrays.
Solution:
Despite the limitation of CURLOPT_POSTFIELDS, there is a workaround using the http_build_query_for_curl() function. This function recursively converts a multidimensional array into a flat array suitable for curl_setopt().
Example Code:
<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>
Output:
Array ( [name[first][0]] => Natali [name[first][1]] => Yura )
This flat array can then be passed to curl_setopt() as the third argument, successfully posting the multidimensional array via CURL.
The above is the detailed content of How to Post Multidimensional Arrays via PHP and CURL?. For more information, please follow other related articles on the PHP Chinese website!