Home > Backend Development > PHP Tutorial > How to Post Multidimensional Arrays via PHP and CURL?

How to Post Multidimensional Arrays via PHP and CURL?

Mary-Kate Olsen
Release: 2024-10-23 08:16:02
Original
518 people have browsed it

How to Post Multidimensional Arrays via PHP and CURL?

Posting 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>
Copy after login

Output:

Array
(
    [name[first][0]] => Natali
    [name[first][1]] => Yura
)
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template