http_build_query

(PHP 5, PHP 7)

http_build_queryГенерирует URL-кодированную строку запроса

Описание

string http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )

Генерирует URL-кодированную строку запроса из предоставленного ассоциативного (или индексного) массива.

Список параметров

query_data

Может быть массивом или объектом, содержащим свойства.

Если query_data массив, то он может быть простой одномерной структурой, или массивом массивов (который, в свою очередь, может содержать другие массивы).

Если query_data объект, тогда только общедоступные (public) свойства будут включены в результат.

numeric_prefix

Если числовые индексы используются в базовом массиве и этот параметр указан, то будет добавлен числовой индекс только для элементов в базом массиве.

Это позволяет обеспечить допустимые имена переменных, в которые позже данные декодируются PHP или другим CGI приложением.

arg_separator

arg_separator.output Используется в качестве разделителя аргументов, если этот параметр указан.

enc_type

По умолчанию, PHP_QUERY_RFC1738.

Если enc_type равен PHP_QUERY_RFC1738, тогда кодирование осуществляется по » RFC 1738 и типу контента application/x-www-form-urlencoded, который подразумевает, что пробелы кодируются как символы "плюс"(+).

Если enc_type равен PHP_QUERY_RFC3986, тогда кодирование осуществляется в соответствии с » RFC 3986, и пробелы будут кодированы как %20.

Возвращаемые значения

Возвращает URL-кодированную строку.

Список изменений

Версия Описание
5.4.0 Добавлен параметр enc_type.
5.1.3 Квадратные скобки экранируются.
5.1.2 Добавлен параметр arg_separator.

Примеры

Пример #1 Простой пример использования http_build_query()

<?php
$data 
= array('foo'=>'bar',
              
'baz'=>'boom',
              
'cow'=>'milk',
              
'php'=>'hypertext processor');

echo 
http_build_query($data) . "\n";
echo 
http_build_query($data'''&amp;');

?>

Результат выполнения данного примера:

foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor

Пример #2 Пример использования http_build_query() с числовыми индексами элементов.

<?php
$data 
= array('foo''bar''baz''boom''cow' => 'milk''php' =>'hypertext processor');

echo 
http_build_query($data) . "\n";
echo 
http_build_query($data'myvar_');
?>

Результат выполнения данного примера:

0=foo&1=bar&2=baz&3=boom&cow=milk&php=hypertext+processor
myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=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

Замечание:

Только числовой индексированный элемент "CEO" в базовом массиве получил префикс. Другие числовые индексы, найденные в pastimes, не требуют строкового префикса чтобы быть допустимым именем переменной.

Пример #4 Пример использования http_build_query() с объектом

<?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);
?>

Результат выполнения данного примера:

pub=publicParent&pub_bar%5Bpub%5D=publicChild

Смотрите также

  • parse_str() - Разбирает строку в переменные
  • parse_url() - Разбирает URL и возвращает его компоненты
  • urlencode() - URL-кодирование строки
  • array_walk() - Применяет заданную пользователем функцию к каждому элементу массива

Коментарии

Автор:
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=1
2006-01-10 01:57:07
http://php5.kiev.ua/manual/ru/function.http-build-query.html
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);}
?>
2007-08-27 04:15:13
http://php5.kiev.ua/manual/ru/function.http-build-query.html
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.
2009-08-26 22:24:00
http://php5.kiev.ua/manual/ru/function.http-build-query.html
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($chCURLOPT_POSTtrue);
   
curl_setopt($chCURLOPT_POSTFIELDS$post_url);
   
curl_exec($ch);
?>

Note that at the final page that processes the POST data, you should be properly filtering/escaping it.
2010-01-21 15:31:17
http://php5.kiev.ua/manual/ru/function.http-build-query.html
on my install of PHP 5.3, http_build_query() seems to use &amp; 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.
2010-03-11 13:51:26
http://php5.kiev.ua/manual/ru/function.http-build-query.html
Автор:
As noted before, with php5.3 the separator is &amp; 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 &amp; might not be handled properly.

To overcome this specify:

http_build_query($array, '', '&');

and NOT

http_build_query($array); //gives &amp; to some servers
2011-02-08 14:11:49
http://php5.kiev.ua/manual/ru/function.http-build-query.html
Автор:
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
2012-07-19 18:57:12
http://php5.kiev.ua/manual/ru/function.http-build-query.html
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!
2013-03-01 17:38:11
http://php5.kiev.ua/manual/ru/function.http-build-query.html
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);
2013-04-01 13:45:45
http://php5.kiev.ua/manual/ru/function.http-build-query.html
Автор:
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>
2013-04-23 14:27:04
http://php5.kiev.ua/manual/ru/function.http-build-query.html
Автор:
instead of some other suggestions that did not work for me, I found that the best way to build POST content (e.g. for stream_context_create) is urldecode(http_build_query($query))
2013-07-16 23:51:30
http://php5.kiev.ua/manual/ru/function.http-build-query.html
While this is not documented, this http_build_query can return FALSE on some inputs:
<?php
 
//gives bool(false)
 
var_dump(http_build_query('whatever'));
?>
2013-12-10 12:41:44
http://php5.kiev.ua/manual/ru/function.http-build-query.html
Автор:
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
2015-03-01 12:41:16
http://php5.kiev.ua/manual/ru/function.http-build-query.html
Not recommending to eliminate the numeric indices like:
'arg[0]' --> 'arg[]'

The reason is this function will not include null values in the result string:

        $data = array(
            'arg' => array(
                null,
                2,
                3
            )
        );
        echo http_build_query($data);

The output is something like "arg[1]=2&arg[2]=3";
2015-06-12 07:35:48
http://php5.kiev.ua/manual/ru/function.http-build-query.html
Be careful about Example 1 -- it is exactly how *not* to implement things.

& as a separator is the URL encoding.
&amp; is HTML encoding.

You should HTML encode your URL if embedding it in a web page. This is more involved than just replacing & with &amp;. Doing as this example suggests is a security hole waiting to happen.
2015-07-16 02:04:17
http://php5.kiev.ua/manual/ru/function.http-build-query.html
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);
2015-11-17 08:47:34
http://php5.kiev.ua/manual/ru/function.http-build-query.html
Автор:
Params with false value will be changed to zero in result string.

<?php
$arr 
= ['foo' => false];
echo 
http_build_query($arr);
?>

will produce:

foo=0
2016-02-01 05:22:59
http://php5.kiev.ua/manual/ru/function.http-build-query.html
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
2017-02-20 14:27:06
http://php5.kiev.ua/manual/ru/function.http-build-query.html
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) {

// 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;

}
?>
2017-08-23 17:51:55
http://php5.kiev.ua/manual/ru/function.http-build-query.html
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=0
2018-01-05 18:39:18
http://php5.kiev.ua/manual/ru/function.http-build-query.html
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$xmlhttp_build_query$xml ) );
/* Outputs:
object(SimpleXMLElement)#1 (2) {
  ["key"]=>
  object(SimpleXMLElement)#2 (0) {
  }
  ["key2"]=>
  string(6) "value2"
}
string(11) "key2=value2"
*/
?>
2018-02-08 03:26:43
http://php5.kiev.ua/manual/ru/function.http-build-query.html
When using http_build_query($args) where $args is an array; note that there is a limit to the size of array. See max_input_vars in your php.ini to increase this size.
2018-11-20 17:42:29
http://php5.kiev.ua/manual/ru/function.http-build-query.html
Автор:
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
?>
2019-06-06 11:23:59
http://php5.kiev.ua/manual/ru/function.http-build-query.html
It's not mentioned in the documentation, but when calling http_build_query on an object, public null fields are ignored.

<?php

class {
    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); // publicNotNull=2
?>
2020-06-03 19:52:10
http://php5.kiev.ua/manual/ru/function.http-build-query.html

    Поддержать сайт на родительском проекте КГБ