我必须用文件发送数组数据。仅使用数据即可正常工作:
$client->post('http://xxx/', [
'form_params' => [
[
'data' => ['id' => 1234, 'name' => 'nombre'],
'valid' => true
]
]
]);
但是由于我不能将“form_params”与“multipart”一起使用,如何发送包含数组和 bool 数据的文件?
我试过:
$client->post('http://xxx/', [
'multipart' => [
[
'name' => 'myfile',
'contents' => fopen('my_file.txt', 'r'),
],
[
'name' => 'data',
'contents' => ['id' => 1234, 'name' => 'nombre'],
]
[
'name' => 'valid',
'contents' => true,
]
],
]);
但我得到一个错误,因为“内容”不接受 bool 值或数组值。
我需要一些帮助。
谢谢
更新: 我无法解决问题,最后我不得不使用一个不是很好的解决方案,包括作为查询字符串的表单提交参数并仅使用 Multipart。像这样的东西:
$client->post('http://xxx?id=1234&name=nombre', [
'multipart' => [
[
'name' => 'myfile',
'contents' => fopen('my_file.txt', 'r'),
],
],
]);
最佳答案
根据 Guzzle 文档:
The value of multipart is an array of associative arrays, each containing the following key value pairs:
- name: (string, required) the form field name
- contents: (StreamInterface/resource/string, required) The data to use in the form element.
- headers: (array) Optional associative array of custom headers to use with the form element.
- filename: (string) Optional string to send as the filename in the part.
所以看起来它只接受内容的字符串(直接或作为流)。他们可能的理由是,由于它是一个多部分表单,您将分别发送每个数据点,如下所示...
$client->post('http://xxx/', [
'multipart' => [
[
'name' => 'myfile',
'contents' => fopen('my_file.txt', 'r'),
],
[
'name' => 'id',
'contents' => '1234',
],
[
'name' => 'name',
'contents' => 'nombre',
],
[
'name' => 'valid',
'contents' => 'true',
]
],
]);
在不知道数据是如何被解析的情况下,我不能肯定地说这是一个可行的选择,但由于它接受自定义 header ,您可以将其作为 JSON 数组(以字符串形式)发送,然后设置内容类型:
$client->post('http://xxx/', [
'multipart' => [
[
'name' => 'myfile',
'contents' => fopen('my_file.txt', 'r'),
],
[
'name' => 'data',
'contents' => '{"id":1234, "name":"nombre"}',
'headers' => ['Content-Type' => 'text/x-json']
],
[
'name' => 'valid',
'contents' => 'true',
]
],
]);
另一种选择是直接使用 cURL,但我确定您希望避免这种情况,因为您正在使用 Guzzle。
更新
这不是我亲自测试过的东西,但这是您可以尝试的另一件事...(实际上我应该首先想到这一点)。
$client->post('http://xxx/', [
'multipart' => [
[
'name' => 'myfile',
'contents' => fopen('my_file.txt', 'r'),
],
[
'name' => 'data',
'contents' => 'id=1234&name=nombre',
'headers' => ['Content-Type' => 'text/plain; charset=ISO-8859-1']
],
[
'name' => 'valid',
'contents' => true,
]
],
]);
关于php - Guzzle 6 : upload files with array data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34534024/