Svish Svish - 4 months ago 23
HTTP Question

HTTP build query with PHP_QUERY_RFC3986 before PHP 5.4

I thought I would be able to use the easy

http_build_query
to encode some GET parameters from an array, but apparently the
enc_type
seems to have been added in PHP 5.4. Unfortunately I'm on PHP 5.3.10.

Problem is that I need the parameters encoded with spaces being
%20
and not
+
. Any good nice quick solutions of encoding the parameters correctly without using
http_build_query
?

Answer

Since the URL is encoded when http_build_query returns, so that + are always and only spaces, you can just chain it with str_replace:

$query = str_replace('+', '%20', http_build_query($arr));

If you don't want to encode the ~ as well:

$query = str_replace(
    array('+', '%7E'), 
    array('%20', '~'), 
    http_build_query($arr)
);