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
?
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)
);
You can use de PHP_QUERY_RFC3986 flag.
$query = http_build_query($query_data, null, null, PHP_QUERY_RFC3986);
You could also pass the query string through the rawurlencode function. Available in 5.3 it encodes to RFC 3986:
http://www.php.net/manual/en/function.rawurlencode.php
Slightly more concise version of @cwd's answer.
public function httpBuildQuery3986(array $params, $sep = '&')
{
$parts = array();
foreach ($params as $key => $value) {
$parts[] = sprintf('%s=%s', $key, rawurlencode($value));
}
return implode($sep, $parts);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With