Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php url query nested array with no index

I'm working with a third party API that receives several parameters which must be encoded like this:

text[]=Hello%20World&text[]=How%20are%20you?&html[]=<p>Just%20fine,%20thank%20you</p>

As you can see this API can accept multiple parameters for text, and also for HTML (not in the sample call).

I have used http_build_query to correctly build a query string for other APIs

$params['text'][] = 'Hello World';
$params['text'][] = 'How are you?';
$params['html'][] = '<p>Just fine, thank you</p>';

$http_query = http_build_query($params);

The problem with this approach is that it will build a query string with the numeric index:

text[0]=Hello%20World&text[1]=How%20are%20you?&html[0]=<p>Just%20fine,%20thank%20you</p>

unfortunately the API I'm working with doesn't like the numeric index and fails.

Is there any php function/class-method that can help me build a query like this quickly?

Thank you

like image 227
Onema Avatar asked Aug 16 '12 22:08

Onema


2 Answers

I very much agree with the answer by RiaD, but you might run into some problems with this code (sorry I can't just make this a comment due to lack of rep).

First off, as far as I know http_build_query returns an urlencode()'d string, which means you won't have [ and ] but instead you'll have %5B and %5D.

Second, PHP's PCRE engine recognizes the '[' character as the beginning of a character class and not just as a simple '[' (PCRE Meta Characters). This may end up replacing ALL digits from your request with '[]'.

You'll more likely want something like this:

preg_replace('/\%5B\d+\%5D/', '%5B%5D', http_build_query($params));

In this case, you'll need to escape the % characters because those also have a special meaning. Provided you have a string with the actual brackets instead of the escapes, try this:

preg_replace('/\[\d+\]/', '[]', $http_query);
like image 115
michaelxor Avatar answered Oct 06 '22 08:10

michaelxor


I don't know a standard way to do it (I think there is no such way), but here's an ugly solution:

Since [] is encoded by http_build_query, you may generate string with indices and then replace them.

preg_replace('/(%5B)\d+(%5D=)/i', '$1$2', http_build_query($params));
like image 32
RiaD Avatar answered Oct 06 '22 07:10

RiaD