You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止Guzzle在POST请求多值字段名后自动追加[]符号?

解决方案

Guzzle 默认的form_params参数处理多值字段时,会自动追加方括号和索引,要实现foo=hello&foo=world格式的参数,有两种成熟的实现方式:

方法1:手动构造表单请求体

直接手动拼接编码后的表单字符串,跳过Guzzle默认的参数格式化逻辑:

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

$params = [
    'foo' => ['hello', 'world']
];
$formItems = [];
foreach ($params as $key => $values) {
    foreach ((array)$values as $val) {
        $formItems[] = urlencode($key) . '=' . urlencode($val);
    }
}
$postBody = implode('&', $formItems);

$client->request('POST', '', [
    'body' => $postBody
]);

方法2:使用Guzzle自带的DuplicateAggregator聚合器

利用Guzzle内置的查询参数聚合器实现,不用手动处理编码逻辑,代码更简洁:

<?php
use GuzzleHttp\Query;
use GuzzleHttp\Aggregator\DuplicateAggregator;

$client = new \GuzzleHttp\Client([
    'base_uri' => 'https://www.example.com/test',
]);

$query = new Query([
    'foo' => ['hello', 'world']
]);
// 配置为重复键模式,不追加方括号
$query->setAggregator(new DuplicateAggregator());

$client->request('POST', '', [
    'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
    ],
    'body' => (string)$query
]);

两种方法最终生成的请求参数格式都符合要求,可正常适配Google Forms等不接受带方括号参数的服务。

内容的提问来源于stack exchange,提问作者reformed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:18:04