Params with null value do not present in result string.
<?php
$arr = array('test' => null, 'test2' => 1);
echo http_build_query($arr);
?>
will produce:
test2=1http_build_query
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
http_build_query
Референца за `function.http-build-query.php` со подобрена типографија и навигација.
http_build_query
класата mysqli_driver
http_build_query — Generate URL-encoded query string
= NULL
array|object
$data,string
$numeric_prefix = "",?string
$arg_separator = null,int
$encoding_type = PHP_QUERY_RFC1738): string
Генерира URL-кодиран стринг за прашање
Параметри
data-
Генерира URL-кодиран стринг за прашање од дадениот асоцијативен (или индексиран) список.
Враќа
dataМоже да биде список или објект што содржи својства.Враќа
dataако е список, може да биде едноставна еднодимензионална структура, или список од списоци (кои пак може да содржат други списоци). numeric_prefix-
ако е објект, тогаш само јавните својства ќе бидат вклучени во резултатот.
Ако се користат нумерички индекси во основниот список и овој параметар е обезбеден, тој ќе биде претставен пред нумеричкиот индекс за елементите во основниот список само.
arg_separator-
Ова е наменето да овозможи легални имиња на променливи кога податоците подоцна ќе бидат декодирани од PHP или друга CGI апликација.
null, arg_separator.output Разделувач на аргументи. Ако не е поставен или encoding_type-
Стандардно,
PHP_QUERY_RFC1738.Враќа
encoding_typeisPHP_QUERY_RFC1738се користи за одвојување на аргументи. Кодирањето се врши според Пример #4 Споредување на вратената вредност на includeapplication/x-www-form-urlencoded» RFC 1738+типот на медиум, што подразбира дека празнините се кодираат како знаци плус (Враќа
encoding_typeisPHP_QUERY_RFC3986, тогаш кодирањето се врши по Кодирањето се врши според» RFC 3986%20).
Вратени вредности
, тогаш кодирањето се врши според
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.4.0 |
Пред PHP 8.4.0, BackedEnum својства на
data Враќа URL-кодиран стринг.
|
| 8.0.0 |
arg_separator сега е null.
|
Примери
беа претворени во објекти, наместо нивните скаларни еквиваленти. http_build_query()
<?php
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'cow' => 'milk',
'null' => null,
'php' => 'hypertext processor'
);
echo http_build_query($data) . "\n";
echo http_build_query($data, '', '&');
?>Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред
foo=bar&baz=boom&cow=milk&php=hypertext+processor foo=bar&baz=boom&cow=milk&php=hypertext+processor
Пример #2 http_build_query() Пример #1 Едноставна употреба на
<?php
$data = array('foo', 'bar', 'baz', null, 'boom', 'cow' => 'milk', 'php' => 'hypertext processor');
echo http_build_query($data) . "\n";
echo http_build_query($data, 'myvar_');
?>Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред
0=foo&1=bar&2=baz&4=boom&cow=milk&php=hypertext+processor myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_4=boom&cow=milk&php=hypertext+processor
Пример #3 http_build_query() со нумерички индексирани елементи.
<?php
$data = array(
'user' => array(
'name' => 'Bob Smith',
'age' => 47,
'sex' => 'M',
'dob' => '5/12/1956'
),
'pastimes' => array('golf', 'opera', 'poker', 'rap'),
'children' => array(
'bobby' => array('age'=>12, 'sex'=>'M'),
'sally' => array('age'=>8, 'sex'=>'F')
),
'CEO'
);
echo http_build_query($data, 'flags_');
?>со сложени списоци
user%5Bname%5D=Bob+Smith&user%5Bage%5D=47&user%5Bsex%5D=M& user%5Bdob%5D=5%2F12%2F1956&pastimes%5B0%5D=golf&pastimes%5B1%5D=opera& pastimes%5B2%5D=poker&pastimes%5B3%5D=rap&children%5Bbobby%5D%5Bage%5D=12& children%5Bbobby%5D%5Bsex%5D=M&children%5Bsally%5D%5Bage%5D=8& children%5Bsally%5D%5Bsex%5D=F&flags_0=CEO
Забелешка:
Горниот пример ќе прикаже: (превртен збор за читливост)
низа. Претходниот пример може да се преработи како: http_build_query() Само нумеричкиот елемент во основниот список "CEO" доби префикс. Другите нумерички индекси, пронајдени под хоби, не бараат стринг префикс за да бидат легални имиња на променливи.
<?php
class parentClass {
public $pub = 'publicParent';
protected $prot = 'protectedParent';
private $priv = 'privateParent';
public $pub_bar = null;
protected $prot_bar = null;
private $priv_bar = null;
public function __construct(){
$this->pub_bar = new childClass();
$this->prot_bar = new childClass();
$this->priv_bar = new childClass();
}
}
class childClass {
public $pub = 'publicChild';
protected $prot = 'protectedChild';
private $priv = 'privateChild';
}
$parent = new parentClass();
echo http_build_query($parent);
?>Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред
pub=publicParent&pub_bar%5Bpub%5D=publicChild
Види Исто така
- parse_str() - Парсирај стринг како URL query стринг
- parse_url() - Парсирај URL и врати ги неговите компоненти
- urlencode() - URL-кодира стринг
- array_walk() - Применете корисничка функција на секој член од низа
Белешки од корисници 11 белешки
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);if you send boolean values it transform in integer :
$a = [teste1= true,teste2=false];
echo http_build_query($a)
//result will be teste1=1&teste2=0This 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);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) // v=5.63
setlocale(LC_ALL, 'ru_RU');
http_build_query($params) // v=5,63 mind the comma
?>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 serversIf 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) {
// mimic the behavior of $_GET, see also RFC 1738 and 3986.
$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;
}?>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=23Be 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.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.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