百科狗-知识改变命运!
--

http_build_query() - php 网址URL函数

乐乐1年前 (2023-11-21)阅读数 23#技术干货
文章标签数组

http_build_query()

(PHP 5, PHP 7)

生成 URL-encode 之后的请求字符串

说明

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

使用给出的关联(或下标)数组生成一个经过 URL-encode 的请求字符串。

参数

$query_data

可以是数组或包含属性的对象。

http_build_query() - php 网址URL函数

一个$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。

范例

Example #1http_build_query()使用示例

以上例程会输出:

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

Example #2http_build_query()使用数字下标的元素

以上例程会输出:

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

Example #3http_build_query()使用复杂的数组

这会输出:(为了可读性,字已经换行了)

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

Note:

只有基础数组中的数字下标元素“CEO”才获取了前缀,其它数字下标元素(如 pastimes 下的元素)则不需要为了合法的变量名而加上前缀。

Example #4http_build_query()使用对象

以上例程会输出:

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.

will produce:
test2=1
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);
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
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
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);
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
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:

You can then use this to pass along POST data in CURL.

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
Correct implementation of coding the array of params without indexes (valdikks fixed code - didnt work for inner arrays):
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);
    }
Number to string conversion occured in  is affected by locale settings, which might not be obvious. 
While http_build_query can also be used to encode most classes, into a query string, SimpleXML Elements with  values are picked up as empty arrays, and therefore aren't included naturally. 
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.
If you need the inverse functionality, and (like me) you cannot use pecl_http, you may want to use something akin to the following. 
Warning: Different arrays may return the same result
$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 '
'; var_dump($a2); echo '
'; echo $q1; echo '
'; echo $q2; echo '
';
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
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.
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: 
Params with false value will be changed to zero in result string.

will produce:
foo=0
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.
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";
If you need only key+value pairs, you can use this:

Result: type=welcome;message=Hello World!
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))
While this is not documented, this http_build_query can return FALSE on some inputs: 

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)