使用 CURL 发布多维数组并在服务器上获取结果 [英] Post multidimensional array using CURL and get the result on server

查看:30
本文介绍了使用 CURL 发布多维数组并在服务器上获取结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 CURL 从我的本地机器向服务器发送数据.并且数据是多维数组.

I am sending data from my local machine to server using CURL. And the data is multidimensional array.

Array
(
[0] => stdClass Object
    (
        [id] => 1
    )
[1] => stdClass Object
    (
        [id] => 0
    )
[2] => stdClass Object
    (
        [id] => 11
    )
)

我使用下面的代码发送数据.

I am using this below code for sending the data.

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, "my_url");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array);  // $array is my above data

但是在服务器上,当我尝试将此传入数据放入文件或只是 print_r 时,它给了我以下输出

But at server when I try to put this incoming data to file or just print_r it gives me this below output

Array
(
[0] => Array
[1] => Array
[2] => Array
)

但我想要多维输出.

我尝试了 print_r($_POST[0]) 但它只给出了 Array 文本.

I tried with print_r($_POST[0]) but it gives only Array text.

推荐答案

cURL 只能接受一个简单的键值对数组,其中值是字符串,它不能接受像你这样的对象数组.但是它确实接受现成的 POST 数据字符串,因此您可以自己构建字符串并传递它:

cURL can only accept a simple key-value paired array where the values are strings, it can't take an array like yours which is an array of objects. However it does accept a ready made string of POST data, so you can build the string yourself and pass that instead:

$str = http_build_query($array);

...

curl_setopt($ch, CURLOPT_POSTFIELDS, $str);

接收端的print_r($_POST)会显示:

Array
(
    [0] => Array
        (
            [id] => 1
        )

    [1] => Array
        (
            [id] => 0
        )

    [2] => Array
        (
            [id] => 11
        )

)

这篇关于使用 CURL 发布多维数组并在服务器上获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆