日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

php http build query

發布時間:2023/10/19 php 234 如意码农
生活随笔 收集整理的這篇文章主要介紹了 php http build query 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

http_build_query

(PHP 5, PHP 7)

http_build_query — 生成 URL-encode 之后的請求字符串

說明¶

string http_build_query ( mixed $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, '', '&amp;');

?>

以上例程會輸出:

foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&amp;baz=boom&amp;cow=milk&amp;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() - 使用用戶自定義函數對數組中的每個元素做回調處理
 add a note

User Contributed Notes 19 notes

up
down
71

Ilya Rudenko¶

11 years ago
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

up
down
15

itsadok at gmail dot com¶

2 years ago
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);

up
down
21

Anonymous¶

6 years ago
As noted before, with php5.3 the separator is &amp; 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 &amp; might not be handled properly.

To overcome this specify:

http_build_query($array, '', '&');

and NOT

http_build_query($array); //gives &amp; to some servers

up
down
29

eric dot muyser at gmail dot com¶

4 years ago
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);

up
down
9

Vitaly Dyatlov¶

4 years ago
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>

up
down
12

anonymous¶

5 years ago
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

up
down
6

irish [-@-] ytdj [-dot-] ca¶

7 years ago
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.

up
down
1

james at dimensionengineering dot com¶

2 years ago
Be careful about Example 1 -- it is exactly how *not* to implement things.

& as a separator is the URL encoding.
&amp; is HTML encoding.

You should HTML encode your URL if embedding it in a web page. This is more involved than just replacing & with &amp;. Doing as this example suggests is a security hole waiting to happen.

up
down
1

chat dot noir at arcor dot de¶

4 months ago
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;

}?>

up
down
0

rmaslo at archa dot cz¶

10 months ago
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

up
down
0

Mark Simon¶

2 years ago
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

up
down
0

netrox at aol dot com¶

8 years ago
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.

up
down
-1

joelhy¶

1 year ago
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

up
down
-1

joey dot qiang at innomative dot com¶

2 years ago
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";

up
down
-2

valdikss at gmail dot com¶

10 years ago
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);}
?>

up
down
-2

v0idnull[try_to_spam_me_now] at gee-mail dot co¶

7 years ago
on my install of PHP 5.3, http_build_query() seems to use &amp; 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.
up
down
-7

stocki dot r at gmail dot com¶

4 years ago
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!

up
down
-7

Kirils Solovjovs¶

4 years ago
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))
up
down
-34

jakub dot lopuszanski at nasza-klasa dot pl¶

4 years ago
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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。