Params with null value do not present in result string.
<?
$arr = array('test' => null, 'test2' => 1);
echo http_build_query($arr);
?>
will produce:
test2=1
http_build_query
(PHP 5)
http_build_query — Erstellen eines URL-kodierten Query-Strings
Beschreibung
$formdata
[, string $numeric_prefix
[, string $arg_separator
]] )Erstellt einen URL-kodierten Query-String aus einem gegebenen assoziativen (oder indexierten) Array.
Parameter-Liste
-
formdata -
Kann ein Array oder ein Objekt sein, das Eigenschaften enthält.
Das Array kann eine einfache eindimensionale Struktur haben, oder ein Array aus Arrays sein (die wiederum weitere Arrays enthalten können).
-
numeric_prefix -
Wenn numerische Indizes im äußeren Array verwendet werden und ein
numeric_prefixangegeben wurde, wird dieser nur den numerischen Schlüsseln im äußeren Array vorangestellt.Dieser Weg wurde gewählt, um gültige Variablennamen zu erhalten, wenn die Daten später von PHP oder einer anderen CGI-Applikation dekodiert werden.
-
arg_separator -
arg_separator.output wird verwendet, um die Argumente voneinander zu trennen, es sei denn, dass der Parameter angegeben ist. In diesem Falle wird letzteres verwendet.
Rückgabewerte
Gibt einen URL-kodierten String zurück.
Changelog
| Version | Beschreibung |
|---|---|
| 5.1.2 |
arg_separator-Parameter hinzugefügt.
|
| 5.1.3 | Eckige Klammern werden maskiert. |
Beispiele
Beispiel #1 Einfache Verwendung von http_build_query()
<?php
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milch',
'php'=>'hypertext processor');
echo http_build_query($data); // foo=bar&baz=boom&cow=milch&php=hypertext+processor
echo http_build_query($data, '', '&'); // foo=bar&baz=boom&cow=milch&php=hypertext+processor
?>
Beispiel #2 http_build_query() mit numerischen Index-Elementen.
<?php
$data = array('foo', 'bar', 'baz', 'boom', 'kuh' => 'milch', 'php' =>'hypertext processor');
echo http_build_query($data) . "\n";
echo http_build_query($data, 'meineVariable_');
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
0=foo&1=bar&2=baz&3=boom&kuh=milch&php=hypertext+processor meineVariable_0=foo&meineVariable_1=bar&meineVariable_2=baz&meineVariable_3=boom&kuh=milch&php=hypertext+processor
Beispiel #3 http_build_query() mit verschachtelten Arrays
<?php
$data = array('user'=>array('name'=>'Bob Smith',
'alter'=>47,
'geschlecht'=>'M',
'geb'=>'5/12/1956'),
'hobbies'=>array('golf', 'opera', 'poker', 'rap'),
'kinder'=>array('bobby'=>array('alter'=>12,
'geschlecht'=>'M'),
'sally'=>array('alter'=>8,
'geschlecht'=>'F')),
'CEO');
echo http_build_query($data, 'flags_');
?>
Ausgabe: (für bessere Lesbarkeit umgebrochen!)
user[name]=Bob+Smith&user[alter]=47&user[geschlecht]=M&user[geb]=5%2F12%2F1956& hobbies[0]=golf&hobbies[1]=opera&hobbies[2]=poker&hobbies[3]=rap& kinder[bobby][alter]=12&kinder[bobby][geschlecht]=M&kinder[sally][alter]=8& kinder[sally][geschlecht]=F&flags_0=CEO
Hinweis:
Nur das numerische Indexelement im äußeren Array "CEO" erhält ein Prefix. Die anderen numerischen Indizes unterhalb von hobbies benötigen kein String-Prefix, um einen gültigen Variablennamen darzustellen.
Beispiel #4 Verwendung von http_build_query() mit einem Objekt
<?php
class meineKlasse {
var $foo;
var $baz;
function meineKlasse() {
$this->foo = 'bar';
$this->baz = 'boom';
}
}
$data = new meineKlasse();
echo http_build_query($data); // foo=bar&baz=boom
?>
Siehe auch
- parse_str() - Überträgt einen String in Variable
- parse_url() - Analysiert einen URL und gibt seine Bestandteile zurück
- urlencode() - URL-kodiert einen String
- array_walk() - Wendet eine Benutzerfunktion auf jedem Element eines Arrays an
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.
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
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
I noticed that even with the magic quotes disabled, http_build_query() automagically adds slashes to strings.
So, I had to add "stripslashes" to every string variable.
This function is wrong for http!
arrays in http is like this:
files[]=1&files[]=2&...
but function makes like this
files[0]=1&files[1]=2&...
Here is normal function:
<?php
function cr_post($a,$b=\'\',$c=0){
if (!is_array($a)) return false;
foreach ((array)$a as $k=>$v){
if ($c) $k=$b.\"[]\"; elseif (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);}
?>
on my install of PHP 5.3, http_build_query() seems to use & as the default separator. Kind of interesting when combined with stream_context_create() for a POST request, and getting $_POST['amp;fieldName'] on the receiving end.
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>
This function makes like this
files[0]=1&files[1]=2&...
To do it like this:
files[]=1&files[]=2&...
Do this:
$query = http_build_query($query);
$query = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);
If you need only key+value pairs, you can use this:
<?php
$array = array(
"type" => "welcome",
"message" => "Hello World!"
);
echo urldecode(http_build_query($array, '', ';'));
?>
Result: type=welcome;message=Hello World!
