PHP URL函数

PHP http_build_query() 函数从提供的关联(或索引)数组生成 URL 编码的查询字符串。

PHP编程中通过该方法可以构造url请求的参数,这对于我们封装http请求非常有用。

语法

http_build_query(data, numeric_prefix, 
                 arg_separator, encoding_type) 

参数

data必需。 指定数据。它可能是包含属性的数组或对象。
  • 如果data是一个数组,它可以是一维数组或多维数组。
  • 如果data是一个数组对象,则只有公共属性会合并到结果中。
numeric_prefix可选。 数字索引前缀。如果在基本数组中使用数字索引并且提供了此参数,则仅将其添加到基本数组中元素的数字索引之前。
arg_separator可选。 arg_separator.output 用于分隔参数,但可以通过指定此参数来覆盖。 arg_separator.output可以在php.ini中设置。
encoding_type可选。 指定编码类型。默认值为 PHP_QUERY_RFC1738。它可以采用以下值:
  • PHP_QUERY_RFC1738 :根据 RFC 1738 和 application/x-www-form-urlencoded 媒体类型执行编码,这意味着空格被编码为加号 (+)。
  • PHP_QUERY_RFC3986:根据 RFC 3986 执行编码,空格将按百分比编码 (%20)。

返回值

返回 URL 编码的字符串。

示例: http_build_query() 示例

下面的示例显示了http_build_query()函数的简单用法。

<?php
$info = array(
  'lang' => 'php',
  'topic' => 'function-reference',
  'example' => '1',
  'null' => null,
  'php' => 'hypertext processor'
);

echo http_build_query($info)."\n";

//使用#作为参数分隔符
echo http_build_query($info, '', '#');
?> 

上述代码的输出将是:

lang=php&topic=function-reference&example=1&php=hypertext+processor
lang=php#topic=function-reference#example=1#php=hypertext+processor 

示例:使用数字索引数组

下面的示例显示了numeric_prefix参数的用法。

<?php
$info = array('php', 'function-reference', 
              '1', null, 'hypertext processor');

echo http_build_query($info)."\n";

//使用 'myvar_' 作为 numeric_prefix 参数
//将其添加到数字索引之前
echo http_build_query($info, 'myvar_');
?> 

输出上述代码的内容为:

0=php&1=function-reference&2=1&4=hypertext+processor
myvar_0=php&myvar_1=function-reference&myvar_2=1&myvar_4=hypertext+processor 

示例:使用多维数组

多维数组也可以与此函数一起使用,如示例所示下面:

<?php
$info = array(
  'Mike', 
  'age' => 55,
  'children' => array(
    'John' => array('age'=>12, 'gender'=>'M'),
    'Marry' => array('age'=>8, 'gender'=>'F')
));

echo http_build_query($info, 'var_');
?> 

上述代码的输出将是(为便于阅读而自动换行):

var_0=Mike&age=55&children%5BJohn%5D%5Bage%5D=12&
children%5BJohn%5D%5Bgender%5D=M&children%5BMarry%5D
%5Bage%5D=8&children%5BMarry%5D%5Bgender%5D=F 

示例:使用对象

如果使用对象,则只有公共属性才会合并到结果中。考虑下面的示例:

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