多维数组例如:
$post['question'] = 'Are you human?'; $post['answers'] = array('yes','no','maybe'); $post['file'] = '@/path/to/file'; // Output: Array( 'question' => Are you human?,'answers' => Array( '0' => yes,'1' => no,'2' => maybe ),'file' => @/path/to/file )
如果您只是尝试使用CURL中的CURLOPT_POSTFIELDS发布此内容,那么为什么这不起作用有以下几种:
$ch = curl_init(); curl_setopt($ch,CURLOPT_URL,'http://example.com'); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); curl_setopt($ch,CURLOPT_POST,CURLOPT_POSTFIELDS,$post); $response = curl_exec($ch);
首先,CURLOPT_POSTFIELDS的官方PHP description说:
The full data to post in a HTTP “POST”
operation. To post a file,prepend a
filename with @ and use the full path.
This can either be passed as a
urlencoded string like
‘para1=val1¶2=val2&…’ or as an
array with the field name as key and
field data as value. If value is an
array,the Content-Type header will be
set to multipart/form-data.
听起来你可以将任何类型的数组传递给POSTFIELDS吗?错误. POSTFIELDS只接受非标量值,并且在传递多维数组时会阻塞Array to string转换错误.因此,您拥有的唯一其他选项是http_build_query()您的数组能够传递不会阻塞的多维数组.
但是..正如您可以在PHP页面上的注释中看到的那样:
Note: Passing an array to
CURLOPT_POSTFIELDS will encode the
data as multipart/form-data,while
passing a URL-encoded string will
encode the data as
application/x-www-form-urlencoded.
如果将urlencoded字符串传递给POSTFIELDS,则该帖子将不会进行多部分/表单数据编码,从而导致文件上载失败.
因此,将两者与CURL结合起来似乎几乎是不可能的,如果您使用常规HTML表单则不会有问题.
我的问题是:是否有可能绕过这个奇怪的CURL怪癖来发布多维数组和文件上传?
我怀疑你的请求的接收端也是一个PHP脚本.如果,那么你可以提交一个嵌套数组作为其中一个值,如果你自己准备它:
$post['answers[0]'] = "yes"; $post['answers[1]'] = "no"; $post['answers[2]'] = "maybe";
从理论上讲,你只需要没有索引的’answers []’,但这会覆盖前面的值 – 因此只适用于http_build_query.
我不确定PHP中是否有任何HTTP库可以自动执行此操作.