How to Post Multidimensional Arrays via PHP and CURL?
Oct 23, 2024 am 08:16 AMPosting Multidimensional Arrays with 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, &amp;$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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
