函数名:http_build_query()
适用版本:PHP 4, PHP 5, PHP 7
用法:http_build_query() 函数将数组或对象转换为 URL 编码字符串。它可以用于构建查询字符串,特别是在发送 HTTP GET 请求时非常有用。
语法:string http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )
参数:
- query_data:要转换的数组或对象。
- numeric_prefix:可选参数,指定数组键的前缀,用于处理数字数组。
- arg_separator:可选参数,指定用于分隔参数的字符,默认为"&"。
- enc_type:可选参数,指定使用的 URL 编码类型,默认为 PHP_QUERY_RFC1738。
返回值:返回 URL 编码后的字符串。
示例:
- 将关联数组转换为 URL 编码字符串:
$data = array(
'name' => 'John Doe',
'age' => 25,
'email' => 'john@example.com'
);
$queryString = http_build_query($data);
echo $queryString;
输出:
name=John+Doe&age=25&email=john%40example.com
- 使用自定义参数分隔符和前缀:
$data = array(
'colors' => array('red', 'green', 'blue'),
'size' => 'large'
);
$queryString = http_build_query($data, 'param', '|');
echo $queryString;
输出:
param[colors][0]=red|param[colors][1]=green|param[colors][2]=blue¶m[size]=large
- 将对象转换为 URL 编码字符串:
class Person {
public $name;
public $age;
public $email;
}
$person = new Person();
$person->name = 'John Doe';
$person->age = 25;
$person->email = 'john@example.com';
$queryString = http_build_query($person);
echo $queryString;
输出:
name=John+Doe&age=25&email=john%40example.com
注意事项:
- http_build_query() 函数默认使用 RFC 1738 标准进行 URL 编码,如果需要使用 RFC 3986 标准,请将第四个参数 enc_type 设置为 PHP_QUERY_RFC3986。
- 如果 query_data 参数是一个多维数组,http_build_query() 函数会自动使用方括号表示数组的层次结构。如果需要使用其他字符表示数组的层次结构,请使用 numeric_prefix 参数。