Home > OS >  Is there a way to prevent Guzzle from appending [] to field names with multiple values in a POST req
Is there a way to prevent Guzzle from appending [] to field names with multiple values in a POST req

Time:10-05

When using Guzzle to POST a field with multiple values, brackets get appended to the field names:

    <?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 sends this data as foo[0]=hello&foo[1]=world. Is there a way to omit the brackets, so that the data is sent as foo=hello&foo=world? Google Forms, for example, returns a 400 error response if the brackets are included.

CodePudding user response:

There currently is no way to achieve this by using the automatic encoding with post_params, so you'll have to provide your own raw POST body if you need this exact format.

Fortunately, there's a very helpful function in GuzzleHttp\Psr7\Query (which should automatically come installed if you required guzzle through composer), named build, which does exactly what you need.

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',
        ],
    ]),
]);
  • Related