Be careful if you're assuming that arg_separator defaults to "&".
For me, with my xampp installation and PHP 5.2.1, this was scary:
[php.ini]
; The separator used in PHP generated URLs to separate arguments.
; Default is "&".
arg_separator.output = "&"
... as it gave me a complete headache debugging something, as I expected the string length to be the length of the string my browser was displaying. I was so certain arg_separator was "&" because I'd never changed my php.ini that it took me seemingly forever to consider looking at the source code.
D'oh.
This may seem irrelevant at first (and I realise my case is an unusual way of stumbling into this issue), but since, if you run htmlspecialchars() over "&", the result will be "&", DON'T expect a one- or two-parameter http_build_query() to return a query you still have to run through htmlspecialchars().
I suggest using the third parameter to retain your sanity.
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
http_build_query
27-Apr-2007 11:24
03-Feb-2007 10:27
To flyingmeteor,
Your function is pleasingly adequate, however, when comparing the results from your function with the results from the actual function, it has a minor defect. If one uses a special character (e.g. øæåöä) in a key in the $data array, it is not encoded by your function, but it is by the actual one.
This is easily solved by some minor edits:
<?php
if(!function_exists('http_build_query')) {
function http_build_query($data,$prefix=null,$sep='',$key='') {
$ret = array();
foreach((array)$data as $k => $v) {
$k = urlencode($k);
if(is_int($k) && $prefix != null) {
$k = $prefix.$k;
};
if(!empty($key)) {
$k = $key."[".$k."]";
};
if(is_array($v) || is_object($v)) {
array_push($ret,http_build_query($v,"",$sep,$k));
}
else {
array_push($ret,$k."=".urlencode($v));
};
};
if(empty($sep)) {
$sep = ini_get("arg_separator.output");
};
return implode($sep, $ret);
};
};
?>
Forgive my personal coding standard.
22-Dec-2006 12:37
I think it doesnt :( when processing array let say from MySQL db, where array is list of rows (column - value), it generates the first "row" without indexes (post_subject=xxx&post_detail=yyy) while the other rows are indexed well ( 1[post_subject]=xxx&1[post_details]=yyy )
this causes confusion when the array is read back from this string (because the first line, without index is ignored (put to another variable than rest of the array), also count of this array says n+x (N = amount of rows in the array, X = amount of columns in the first row) which is wrong. The correct way should look like
0[post_subject]=xxx&0[post_detail]=yyy
for the first entry and then to continue with the rest
11-Dec-2006 06:46
Here is another equivalent function for users that don't have PHP5 yet, it behaves the same way as the PHP5 counterpart and has one extra parameter for added functionality.
<?php
if (!function_exists('http_build_query')) {
function http_build_query($data, $prefix='', $sep='', $key='') {
$ret = array();
foreach ((array)$data as $k => $v) {
if (is_int($k) && $prefix != null) $k = urlencode($prefix . $k);
if (!empty($key)) $k = $key.'['.urlencode($k).']';
if (is_array($v) || is_object($v))
array_push($ret, http_build_query($v, '', $sep, $k));
else array_push($ret, $k.'='.urlencode($v));
}
if (empty($sep)) $sep = ini_get('arg_separator.output');
return implode($sep, $ret);
}}
?>
08-Mar-2006 04:11
I am concerned about this function's generation of [ and ] in the variable names.
From what I can gather from http://www.faqs.org/rfcs/rfc3986.html (which I believe to be the most recent RFC on the matter), the use of square brackets is illegal here.
To be sure, always use the following:
str_replace(array('[',']'), array('%5B','%5D'), http_build_query($data));
I will also submit a bug, but thought it important to inform users.
08-Mar-2006 03:25
@ xangelusx
You said that "It is actually illegal to set arg_separator.output to & ("and amp ;") as every character is considered a seperator according to the documentation."
I don't think this is correct. arg_separator.input maybe, but not the output. How can PHP encode my URLs (that is what this setting is used for, e.g. on URL rewriting etc.) with more than one separator? It doesn't make sence for that variable.
I have personally used & as a separate for output for years in order to create valid XHTML output via PHP.
I long ago wrote a function to do this for me, but depending on where I use the output, I sometimes want & and sometimes just a plain old & (think putting the value in a href="" versus using it in a Location: header). Unfortunatly, I can see no way to deprecate my function just yet, as this built in function is lacking that distinction (an optional argument would be perfect IMO)
10-Jan-2006 08:57
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
05-Oct-2005 02:03
Dear anonymous, i think that your example is incorrect in some places (or at least is not flexible) and shortly only in names of variables (as $c, $k, etc.) and some spaces and line foldings :), i can explain:
1. I think that next part of code is not wanted here:
<?if (!is_array($a)) return false;?>
because you have (array)$a in foreach! It is possible but not obligatory. Or maybe better to use trigger_error for this situation.
2. You don't use urlencode on key! It's wrong because it can have also unsafe value!
<?if ($c) $k=$b."[".$k."]"; elseif (is_int($k)) $k=$b.$k;?>
this part is wrong because $k can be integer even if $c is not empty. I can want to add numeric_prefix to all indexes in array, but your example will not allow to make it. Here using of elseif is excluded, these both conditions should exist simultaneously.
3. <?http_build_query($v,$k,1);?> - In my opinion it's a very rough error. You use second parameter (as "numeric_prefix" in my example and php manual for this function) for transfer of the current key into next iteration step of recursion. Certainly it's possible and is not of principle, but very not professionally, in my opinion. I use implicit rule: one ought not to violate function logic even inside of the same function one may only expand logic. And my <?http_build_query($v, null, $tmp_key);?> allows to add numeric_prefix to all indexes in array (see point 2), i need just to put $numeric_prefix instead of null into second parameter.
Also i want to extend my previous example because we must use ini_get('arg_separator.output') instead of '&' separator!
<?
if(!function_exists('http_build_query')) {
function http_build_query( $formdata, $numeric_prefix = null, $key = null ) {
$res = array();
foreach ((array)$formdata as $k=>$v) {
$tmp_key = urlencode(is_int($k) ? $numeric_prefix.$k : $k);
if ($key) $tmp_key = $key.'['.$tmp_key.']';
if ( is_array($v) || is_object($v) ) {
$res[] = http_build_query($v, null /* or $numeric_prefix if you want to add numeric_prefix to all indexes in array*/, $tmp_key);
} else {
$res[] = $tmp_key."=".urlencode($v);
}
/*
If you want, you can write this as one string:
$res[] = ( ( is_array($v) || is_object($v) ) ? http_build_query($v, null, $tmp_key) : $tmp_key."=".urlencode($v) );
*/
}
$separator = ini_get('arg_separator.output');
return implode($separator, $res);
}
}
?>
All best!
I made my very own http_build_query function quite some time ago for php 4 and below. Works exactly like the function below; but its just a bit shorter. :P
<?
function http_build_query($a,$b='',$c=0){
if (!is_array($a)) return false;
foreach ((array)$a as $k=>$v){
if ($c) $k=$b."[".$k."]"; elseif (is_int($k)) $k=$b.$k;
if (is_array($v)||is_object($v)) {$r[]=http_build_query($v,$k,1);continue;}
$r[]=$k."=".urlencode($v);
}
return implode("&",$r);
}
?>
29-Sep-2005 01:31
My example of this function for PHP versions < PHP5 without any regular expressions, just cycles, recursion and standard functions. It can work with complex arrays or objects or both combined.
<?php
if(!function_exists('http_build_query')) {
function http_build_query( $formdata, $numeric_prefix = null, $key = null ) {
$res = array();
foreach ((array)$formdata as $k=>$v) {
$tmp_key = urlencode(is_int($k) ? $numeric_prefix.$k : $k);
if ($key) {
$tmp_key = $key.'['.$tmp_key.']';
}
if ( is_array($v) || is_object($v) ) {
$res[] = http_build_query($v, null, $tmp_key);
} else {
$res[] = $tmp_key."=".urlencode($v);
}
}
return implode("&", $res);
}
}
?>
12-May-2005 03:22
This is a workaround for PHP versions < PHP5. It does not work with complex arrays, however.
<?
if (!function_exists('http_build_query')) {
function http_build_query($formdata, $numeric_prefix = "")
{
$arr = array();
foreach ($formdata as $key => $val)
$arr[] = urlencode($numeric_prefix.$key)."=".urlencode($val);
return implode($arr, "&");
}
}
?>
28-May-2004 05:25
This functionality is now implemented in the PEAR package PHP_Compat.
More information about using this function without upgrading your version of PHP can be found on the below link:
http://pear.php.net/package/PHP_Compat