The above example will output:
pub=publicParent&pub_bar%5Bpub%5D=publicChild
parse_str()
- Parses the string into variables
parse_url()
- Parse a URL and return its components
urlencode()
- URL-encodes string
array_walk()
- Apply a user supplied function to every member of an array
itsadok at gmail dot com
¶
8 years ago
Passing null to $arg_separator is the same as passing an empty string, which is probably not what you want.
If you need to change the enc_type, use this:
http_build_query($query, null, '&', PHP_QUERY_RFC3986);
Or possibly this:
http_build_query($query, null, ini_get('arg_separator.output'), PHP_QUERY_RFC3986);
But not this:
// BAD CODE!
http_build_query($query, null, null, PHP_QUERY_RFC3986);
Sergei S.
¶
5 years ago
Number to string conversion occured in
<?php http_build_query
()
?>
is affected by locale settings, which might not be obvious.
<?php
$params
= [
"v"
=>
5.63
];
setlocale
(
LC_ALL
,
'us_En'
);
http_build_query
(
$params
)
setlocale
(
LC_ALL
,
'ru_RU'
);
http_build_query
(
$params
)
?>
Anonymous
¶
13 years ago
As noted before, with php5.3 the separator is & on some servers it seems. Normally if posting to another php5.3 machine this will not be a problem.
But if you post to a tomcat java server or something else the & might not be handled properly.
To overcome this specify:
http_build_query($array, '', '&');
and NOT
http_build_query($array); //gives & to some servers
chat dot noir at arcor dot de
¶
7 years ago
If you need the inverse functionality, and (like me) you cannot use pecl_http, you may want to use something akin to the following.
<?php
function
http_parse_query
(
$Query
) {
$Delimiter
=
ini_get
(
'arg_separator.input'
);
$Params
= array();
foreach (
explode
(
$Delimiter
,
$Query
) as
$NameValue
) {
preg_match
(
'/^(?P<name>[^=\[]*)(?P<indices_present>\[(?P<indices>[^\]]*(\]\[[^\]]*)*)\]?)?(?P<value_present>=(?P<value>.*))?$/'
,
$NameValue
,
$NameValueParts
);
if (!empty(
$NameValueParts
)) {
$Param
=&
$Params
[
$NameValueParts
[
'name'
]];
if (!empty(
$NameValueParts
[
'indices_present'
])) {
$Indices
=
explode
(
']['
,
$NameValueParts
[
'indices'
]);
foreach (
$Indices
as
$Index
) {
if (!
is_array
(
$Param
)) {
$Param
= array();
}
if (
$Index
===
''
) {
$Param
[] = array();
end
(
$Param
);
$Param
=&
$Param
[
key
(
$Param
)];
} else {
if (
ctype_digit
(
$Index
)) {
$Index
= (int)
$Index
; }
if (!
array_key_exists
(
$Index
,
$Param
)) {
$Param
[
$Index
] = array();
}
$Param
=&
$Param
[
$Index
];
}
}
}
if (!empty(
$NameValueParts
[
'value_present'
])) {
$Param
=
urldecode
(
$NameValueParts
[
'value'
]);
} else {
$Param
=
''
;
}
}
}
return
$Params
;
}
?>
anonymous
¶
12 years ago
Is it worth noting that if query_data is an associative array and a value is itself an empty array, or an array of nothing but empty array (or arrays containing only empty arrays etc.), the corresponding key will not appear in the resulting query string?
E.g.
$post_data = array('name'=>'miller', 'address'=>array('address_lines'=>array()), 'age'=>23);
echo http_build_query($post_data);
will print
name=miller&age=23
james at dimensionengineering dot com
¶
9 years ago
Be careful about Example 1 -- it is exactly how *not* to implement things.
& as a separator is the URL encoding.
& is HTML encoding.
You should HTML encode your URL if embedding it in a web page. This is more involved than just replacing & with &. Doing as this example suggests is a security hole waiting to happen.
irish [-@-] ytdj [-dot-] ca
¶
14 years ago
When using the http_build_query function to create a URL query from an array for use in something like curl_setopt($ch, CURLOPT_POSTFIELDS, $post_url), be careful about the url encoding.
In my case, I simply wanted to pass on the received $_POST data to a CURL's POST data, which requires it to be in the URL format. If something like a space [ ] goes into the http_build_query, it comes out as a +. If you're then sending this off for POST again, you won't get the expected result. This is good for GET but not POST.
Instead you can make your own simple function if you simply want to pass along the data:
<?php
$post_url
=
''
;
foreach (
$_POST
AS
$key
=>
$value
)
$post_url
.=
$key
.
'='
.
$value
.
'&'
;
$post_url
=
rtrim
(
$post_url
,
'&'
);
?>
You can then use this to pass along POST data in CURL.
<?php
$ch
=
curl_init
(
$some_url
);
curl_setopt
(
$ch
,
CURLOPT_POST
,
true
);
curl_setopt
(
$ch
,
CURLOPT_POSTFIELDS
,
$post_url
);
curl_exec
(
$ch
);
?>
Note that at the final page that processes the POST data, you should be properly filtering/escaping it.
Mark Simon
¶
9 years ago
As noted, this function omits keys with null values. This could break some code which treats the key as boolean, and so has no value, or other code expecting the array to be populated regardless of value.
A workaround for this is to replace the null values with an empty string:
$data=array(
'a'=>'apple',
'b'=>2,
'c'=>null,
'd'=>'…',
);
// Compensate for fact that http_build_query omits null values
foreach($data as &$datum) if($datum===null) $datum='';
Losing the null-ness of the original is no real loss if it’s supposed to be a real query string. If the null is important, you could use a dummy value instead.
Mark
Vitaly Dyatlov
¶
11 years ago
Correct implementation of coding the array of params without indexes (valdikks fixed code - didnt work for inner arrays):
<code>
function cr_post($a,$b='',$c=0)
{
if (!is_array($a)) return false;
foreach ((array)$a as $k=>$v)
{
if ($c)
{
if( is_numeric($k) )
$k=$b."[]";
else
$k=$b."[$k]";
}
else
{ if (is_int($k))
$k=$b.$k;
}
if (is_array($v)||is_object($v))
{
$r[]=cr_post($v,$k,1);
continue;
}
$r[]=urlencode($k)."=".urlencode($v);
}
return implode("&",$r);
}
</code>
rmaslo at archa dot cz
¶
7 years ago
Warning: Different arrays may return the same result
<CODE>
$a1 = array('x[y]' => array('a'=>1));
$a2 = array('x' => array('y' => array('a'=>1)));
$q1 = http_build_query($a1);
$q2 = http_build_query($a2);
var_dump($a1);
echo '<BR>';
var_dump($a2);
echo '<BR>';
echo $q1;
echo '<BR>';
echo $q2;
echo '<BR>';
</CODE>
Result:
array(1) { ["x[y]"]=> array(1) { ["a"]=> int(1) } }
array(1) { ["x"]=> array(1) { ["y"]=> array(1) { ["a"]=> int(1) } } }
x%5By%5D%5Ba%5D=1
x%5By%5D%5Ba%5D=1
drewdeveloperthomas at gmail dot com
¶
4 years ago
It's not mentioned in the documentation, but when calling http_build_query on an object, public null fields are ignored.
<?php
class
A
{
public
int $publicNotNull
;
public ?
int $publicNull
;
private
string $privateNotNull
;
public function
__construct
()
{
$this
->
publicNotNull
=
2
;
$this
->
privateNotNull
=
"Test"
;
}
}
$a
= new
A
();
echo
http_build_query
(
$a
);
?>
shaun at slickdesign dot com dot au
¶
6 years ago
While http_build_query can also be used to encode most classes, into a query string, SimpleXML Elements with <![CDATA[]]> values are picked up as empty arrays, and therefore aren't included naturally.
<?php
$xml
=
simplexml_load_string
(
'<wrapper><key><![CDATA[value]]></key><key2>value2</key2></wrapper>'
);
var_dump
(
$xml
,
http_build_query
(
$xml
) );
?>