【问题标题】:Is there a way to prevent Guzzle from appending [] to field names with multiple values in a POST request?有没有办法防止 Guzzle 在 POST 请求中将 [] 附加到具有多个值的字段名称?
【发布时间】:2021-11-23 10:15:02
【问题描述】:

当使用 Guzzle 发布具有多个值的字段时,括号会附加到字段名称:

    <?php
    $client = new \GuzzleHttp\Client([
        'base_uri' => 'https://www.example.com/test',
        'headers' => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
     );

    $client->request('POST', '', [
        'form_params' => [
            'foo' => [
                'hello',
                'world',
            ],
        ],
    ]);

Guzzle 将此数据发送为 foo[0]=hello&amp;foo[1]=world。有没有办法省略括号,使数据以foo=hello&amp;foo=world 发送?例如,如果包含括号,Google 表单会返回 400 错误响应。

【问题讨论】:

  • 你试过'form_params'=&gt;['foo'=&gt;'hello','foo'=&gt;'world']吗?
  • 是的,问题在于结果数组将有一个重复的键 foo 并因此用 'world' 覆盖 'hello',只留下 ['foo' =&gt; 'world']form_params

标签: php post guzzle


【解决方案1】:

目前无法通过使用post_params 的自动编码来实现这一点,因此如果您需要这种确切的格式,则必须提供自己的原始 POST 正文。

幸运的是,GuzzleHttp\Psr7\Query 中有一个非常有用的功能(如果您需要通过 composer 进行 guzzle,它应该会自动安装),名为 build,它正是您所需要的。

use GuzzleHttp\Psr7\Query;

$client = new \GuzzleHttp\Client([
    'base_uri' => 'https://www.example.com/test',
    'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
    ]
]);

$client->request('POST', '', [
    'body' => Query::build([
        'foo' => [
            'hello',
            'world',
        ],
    ]),
]);

【讨论】:

  • 太好了,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多