build_query()
云策文档标注
概述
build_query() 是一个用于基于关联或索引数组构建 URL 查询字符串的便捷函数。它内部调用 _http_build_query(),并设置分隔符为 '&',但不会自动对输入数据进行 URL 编码。
关键要点
- 函数用途:基于数组构建 URL 查询字符串,适用于 WordPress 开发中的 URL 处理。
- 参数要求:接受一个数组参数 $data,包含 URL 编码的键/值对,需预先编码。
- 返回值:返回 URL 编码的字符串,可直接用于 URL 查询部分。
- 内部实现:调用 _http_build_query() 函数,设置 urlencode 参数为 false,因此输入数据必须已编码。
- 注意事项:与原生 PHP 的 http_build_query() 不同,此函数不自动编码,需手动处理特殊字符。
代码示例
$myarray = array( 'p%s/n#q?a*e!s p+' => 'percent%slash/number#question?asterisk*exclamate!space plus+end' );
build_query( $myarray ); // 输出:p%s/n#q?a*e!s p+=percent%slash/number#question?asterisk*exclamate!space plus+end
http_build_query( $myarray ); // 输出:p%25s%2Fn%23q%3Fa%2Ae%21s+p%2B=percent%25slash%2Fnumber%23question%3Fasterisk%2Aexclamate%21space+plus%2Bend注意事项
- 输入数组的键和值必须预先进行 URL 编码,否则可能产生无效查询字符串。
- 对于原始数据,建议使用原生 PHP 的 http_build_query() 函数,它会自动处理编码。
- 此函数自 WordPress 2.3.0 版本引入,是 _http_build_query() 的封装,行为类似 PHP5 原生函数。
原文内容
Builds a URL query based on an associative or indexed array.
Description
This is a convenient function for easily building URL queries.
It sets the separator to ‘&’ and uses the _http_build_query() function.
See also
- _http_build_query(): Used to build the query
Parameters
$dataarrayrequired-
URL-encode key/value pairs.
Source
function build_query( $data ) {
return _http_build_query( $data, null, '&', '', false );
}
Changelog
| Version | Description |
|---|---|
| 2.3.0 | Introduced. |
Skip to note 2 content
Andy Schmidt
It’s not clearly spelled out that this function will call _http_build_query() with urlencode = FALSE. So it is assumed that you had previously urlencoded each individual key and value of your input array!
Crucially:
$myarray = array( 'p%s/n#q?a*e!s p+' => 'percent%slash/number#question?asterisk*exclamate!space plus+end' ); build_query( $myarray );will output:
p%s/n#q?a*e!s p+=percent%slash/number#question?asterisk*exclamate!space plus+endIf you have an array with ‘raw’ data, you should use the native PHP function instead:
$myarray = array( 'p%s/n#q?a*e!s p+' => 'percent%slash/number#question?asterisk*exclamate!space plus+end' ); http_build_query( $myarray );will output the proper/usable:
p%25s%2Fn%23q%3Fa%2Ae%21s+p%2B=percent%25slash%2Fnumber%23question%3Fasterisk%2Aexclamate%21space+plus%2Bend