使用 PHP 和 CURL 发布多维数组 [英] Posting multidimensional array with PHP and CURL

查看:28
本文介绍了使用 PHP 和 CURL 发布多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法通过 CURL 将表单数据发布到位于不同主机上的接收 PHP 脚本.

I'm having trouble posting form data via CURL to a receiving PHP script located on a different host.

我收到一个数组到字符串转换错误

这是我发布的数组的print_r:

Array
(
    [name] => Array
    (
        [0] => Jason
        [1] => Mary
        [2] => Lucy
    )
    [id] => 12
    [status] => local
    [file] => @/test.txt
)

这是发生错误的行:

curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);

第三个参数必须是一个数组,因为我需要将 Content-Type 标头设置为 multipart/form-data 作为我我正在通过同一个数组发送文件,因此我无法将数组转换为查询字符串或使用 http_build_query().

The third argument must be an array because I need the Content-Type header to be set to multipart/form-data as I am sending a file via this same array, therefore I cannot convert the array to a query string or use http_build_query().

此外,我无法访问接收主机上的代码,因此无法序列化和反序列化数组.

Also I do not have access to the code on the receiving host so I cannot serialize and unserialize the array.

我假设 name 键的值是一个数组是导致此错误的原因,我还假设 CURLOPT_POSTFIELDS 不支持多维数组.有没有其他办法解决这个问题,还是我注定要失败?

I'm assuming that the value of the name key being an array is the cause for this error, I'm also assuming that CURLOPT_POSTFIELDS doesn't support multidimensional arrays. Is there any other way around this or am I doomed?

提前致谢!

推荐答案

您必须手动构建 POST 字符串,而不是将整个数组传入.然后您可以使用以下命令覆盖 curl 的自动选择的内容标题:

You'd have to build the POST string manually, rather than passing the entire array in. You can then override curl's auto-chose content header with:

curl_setopt($c, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));

序列化/json 化会更容易,但正如您所说,您无法控制接收端,因此您需要做一些额外的工作.

Serializing/json-ifying would be easier, but as you say, you have no control over the receiving end, so you've got a bit of extra work to do.

这篇关于使用 PHP 和 CURL 发布多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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