2
votes

Question:

Anyone know of a way to cajole the Zend\Http\Request (or perhaps it would be in an implementer of Zend\Stdlib\ParametersInterface?) into creating urls where array query arg keys don't contain the indexes.

Background:

I'm attempting to pass an array of values as a query parameter on a GET request using the Zend\Http\Request object.

...
$httpClient = new Zend\Http\Client(); // cURL adapter setup omitted
$request = new Zend\Http\Request();  // set url, set GET method omitted

$myQueryArgArray = [ 
    'key0' => 'val0',
    'key1' => ['val1', 'val2'],
];
$request->getQuery()->fromArray($myQueryArgArray);

$response = $httpClient->send($request);
...

The cURL adapter is sending the request out the door with a url that looks like this:

hostname/path?key0=val0&key1%5B0%5D=val1&key1%5B1%5D=val2

Without the encoding:

hostname/path/?key0=val0&key1[0]=val1&key1[1]=val2

However, the server I'm calling out to fails unless I do NOT pass indexes in the query string. That is, before URL-encoding, I can call my API endpoint with a url like:

hostname/path?key0=val0&key1[]=val1&key1[]=val2

The question (again :):

Anyone know of a way to cajole the Zend\Http\Request (or perhaps it would be in an implementer of Zend\Stdlib\ParametersInterface?) into creating urls where array query arg keys don't contain the indexes.

What I've tried:

I've tried wrapping my array in a Zend\Stdlib\ArrayObject:

...
$myQueryArgArray = [ 
    'key0' => 'val0',
    'key1' => new \Zend\StdLib\ArrayObject(['val1', 'val2']),
];
...

Alas, to no avail.

I know that I accomplish the goal by manually constructing my query string and handing it directly to the Zend\Http\Request object, but I'm looking for a better way than creating my own query strings.

This page seems to indicate that there isn't a standard, so I suppose that neither ZF2 nor my api endpoint are doing it wrong:
How to pass an array within a query string?

1

1 Answers

4
votes

I've looked at the sources and the problem is not the Zend\Http\Request class but the Zend\Http\Client.

Look at line 843 you see a call to the http_build_query function. And on the php.net site you have a solution in the comments:

$query = http_build_query($query);
$query = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);

So the cleanest solution probably would be to extend the Zend\Http\Client class and override the send method.