php http build query
http_build_query
(PHP 5, PHP 7)
http_build_query — 生成 URL-encode 之后的请求字符串
说明¶
$query_data
[, string $numeric_prefix
[, string $arg_separator
[, int $enc_type
= PHP_QUERY_RFC1738
]]] )使用给出的关联(或下标)数组生成一个经过 URL-encode 的请求字符串。
参数¶
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 。 |
范例¶
Example #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, '', '&');
?>
以上例程会输出:
foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&baz=boom&cow=milk&php=hypertext+processor
Example #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
Example #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
Note:
只有基础数组中的数字下标元素“CEO”才获取了前缀,其它数字下标元素(如 pastimes 下的元素)则不需要为了合法的变量名而加上前缀。
Example #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() - 使用用户自定义函数对数组中的每个元素做回调处理

User Contributed Notes 19 notes
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
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
eric dot muyser at gmail dot com¶
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);
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>
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:
<?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.
james at dimensionengineering dot com¶
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.
chat dot noir at arcor dot de¶
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;
}?>
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
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
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.
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
joey dot qiang at innomative dot com¶
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";
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);}
?>
v0idnull[try_to_spam_me_now] at gee-mail dot co¶
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.
stocki dot r at gmail dot com¶
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!
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))
jakub dot lopuszanski at nasza-klasa dot pl¶
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'));
?>
php http build query的更多相关文章
- yii2.0根据query查看sql语句
时间长不用就总是忘记,好记性比不上烂笔头,记录下来备用: Yii::$app->getDb()->getQueryBuilder()->build($query));
- 项目架构开发:数据访问层之Query
接上文 项目架构开发:数据访问层之Repository 上一章我们讲了IRepository接口,这张我们来讲IQuery 根据字面意思就可以知道,这次主要讲数据查询,上一章我们只针对单表做了查询的操 ...
- Docker学习笔记之Docker的Build 原理
0x00 概述 使用 Docker 时,最常用的命令无非是 docker container 和 docker image 相关的子命令,当然最初没有管理类命令(或者说分组)的时候,最常使用的命令也无 ...
- LINQ之路 6:延迟执行(Deferred Execution)
LINQ中大部分查询运算符都有一个非常重要的特性:延迟执行.这意味着,他们不是在查询创建的时候执行,而是在遍历的时候执行(换句话说,当enumerator的MoveNext方法被调用时).让我们考虑下 ...
- URAL 1671 Anansi's Cobweb (并查集)
题意:给一个无向图.每次查询破坏一条边,每次输出查询后连通图的个数. 思路:并查集.逆向思维,删边变成加边. #include<cstdio> #include<cstring> ...
- Linq延迟执行
LINQ中大部分查询运算符都有一个非常重要的特性:延迟执行.这意味着,他们不是在查询创建的时候执行,而是在遍历的时候执行(换句话说,当enumerator的MoveNext方法被调用时).让我们考虑下 ...
- C++关联容器综合应用:TextQuery小程序
本文介绍C++关联容器综合应用:TextQuery小程序(源自C++ Primer). 关于关联容器的概念及介绍,请参考园子里这篇博文:http://www.cnblogs.com/cy568sear ...
- android_orm框架之greenDAO(二)
一.概述 在上次greenDao第一篇文章中,我们对greenDao的使用步骤和基本用法给大家做了介绍,文章链接:http://www.cnblogs.com/jerehedu/p/4304766.h ...
- [bzoj2286] [Sdoi2011消耗战
还是虚树恩..模板都能打挂QAQ 先在原树上预处理出mndis[i],表示根节点到节点i 路径上边权的最小值(就是断开i与根的联系的最小花费) 建完虚树在虚树上跑树形DP..f[i]表示断开 i 所 ...
随机推荐
- 通过生成器yield实现单线程的情况下实现并发运算效果(异步IO的雏形)
一.协程: 1.生成器只有在调用时才会生成相应的数据 2.调用方式有 " str__next__.() str.send() ", 3.并且每调用一次就产生一个值调用到最后一个 ...
- 20165324_mybash
20165324_mybash 实验要求 实验要求: 使用fork,exec,wait实现mybash 写出伪代码,产品代码和测试代码 发表知识理解,实现过程和问题解决的博客(包含代码托管链接) 背景 ...
- 20155203 2016-2017-4 《Java程序设计》第8周学习总结
20155203 2016-2017-4 <Java程序设计>第8周学习总结 教材学习内容总结 1.channel的继承架构 2.position()类似于堆栈操作中的栈顶指针. 3.Pa ...
- flex与j2ee的结合(flex+Spring)
分类: flex spring2012-04-25 02:11 1262人阅读 评论(1) 收藏 举报 flexspringactionscriptjavapropertiesservlet 目录 ...
- Linux笔记 #05# 断开远程连接后保持程序运行
教程:Linux 技巧:让进程在后台可靠运行的几种方法 网上搜索了一下,方法很多,选用最流行的 screen 命令参考:http://man.linuxde.net/screen 1. 安装 root ...
- SNMP学习笔记之SNMPWALK 命令
SNMPWALK是一个通过SNMP GET-NEXT类型PDU,实现对目标AGENT的某指定MIB分支信息进行完整提取输出的命令工作. 命令行: snmpwalk [选项] agent [oid] 选 ...
- Vue学习笔记之Vue指令系统介绍
所谓指令系统,大家可以联想咱们的cmd命令行工具,只要我输入一条正确的指令,系统就开始干活了. 在vue中,指令系统,设置一些命令之后,来操作我们的数据属性,并展示到我们的DOM上. OK,接下来我们 ...
- SQL学习笔记五之MySQL索引原理与慢查询优化
阅读目录 一 介绍 二 索引的原理 三 索引的数据结构 四 聚集索引与辅助索引 五 MySQL索引管理 六 测试索引 七 正确使用索引 八 联合索引与覆盖索引 九 查询优化神器-explain 十 慢 ...
- Sublime Text 3 配置Python3.x
Sublime Text 3 配置Python3.x 一.Package Control 安装: 1,通过快捷键 ctrl+` 或者 View > Show Console 打开控制台,然后粘贴 ...
- 怎样快速掌握一个用你没学过的框架写的PHP项目?
我的思路一般是先搞定框架的route.也就是说,明白一个请求的url地址是对应的哪个controller处理的,找到controller后,再理解一下它的类库加载方案,也就是说一些辅助类以及自己逻辑类 ...