如何阻止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
相关产品推荐
相关产品推荐

