http_build_query

http_build_query(array|object $data, string $numeric_prefix = "", ?string $arg_separator = null, int $enc_type = PHP_QUERY_RFC1738): string

把数组(含嵌套)序列化为 URL 编码的查询串,与 parse_str 互逆;默认空格编码为 +。

C C23

C23
#include <stdio.h>
#include <string.h>

/* 手写百分号编码:RFC 3986 非保留字符直通,其余编码为 %XX(空格编为 %20) */
static void print_encoded(const char *s) {
    for (; *s; s++) {
        if ((*s >= 'A' && *s <= 'Z') || (*s >= 'a' && *s <= 'z') ||
            (*s >= '0' && *s <= '9') || strchr("-_.~", *s) != NULL) {
            putchar(*s);
        } else {
            printf("%%%02X", (unsigned char)*s);
        }
    }
}

int main(void) {
    const char *data[][2] = {{"q", "hello world"}, {"t", "a b&c=d"}};
    for (int i = 0; i < 2; i++) {
        if (i > 0) putchar('&');
        print_encoded(data[i][0]);
        putchar('=');
        print_encoded(data[i][1]);
    }
    putchar('\n');
    return 0;
}
输出
q=hello%20world&t=a%20b%26c%3Dd

C++ C++26

C++26
#include <cctype>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>

// 手写百分号编码:RFC 3986 非保留字符直通,其余编码为 %XX(空格编为 %20)
static std::string encode_component(const std::string &s) {
    std::string out;
    char buf[8];
    for (unsigned char ch : s) {
        if (std::isalnum(ch) || std::strchr("-_.~", static_cast<char>(ch)) != nullptr) {
            out += static_cast<char>(ch);
        } else {
            std::snprintf(buf, sizeof buf, "%%%02X", ch);
            out += buf;
        }
    }
    return out;
}

int main() {
    std::vector<std::pair<std::string, std::string>> data = {
        {"q", "hello world"}, {"t", "a b&c=d"}};
    std::string qs;
    for (size_t i = 0; i < data.size(); i++) {
        if (i > 0) qs += '&';
        qs += encode_component(data[i].first) + "=" + encode_component(data[i].second);
    }
    std::cout << qs << "\n";
    return 0;
}
输出
q=hello%20world&t=a%20b%26c%3Dd

C# v11.0.100

v11.0.100
// Uri.EscapeDataString:RFC 3986 风格,空格编为 %20(不是 +)
static string BuildQuery(IEnumerable<KeyValuePair<string, string>> data) {
    return string.Join("&", data.Select(kv =>
        Uri.EscapeDataString(kv.Key) + "=" + Uri.EscapeDataString(kv.Value)));
}

var data = new[] {
    new KeyValuePair<string, string>("q", "hello world"),
    new KeyValuePair<string, string>("t", "a b&c=d"),
};
Console.WriteLine(BuildQuery(data));
输出
q=hello%20world&t=a%20b%26c%3Dd

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net/url"
)

func main() {
	// url.Values.Encode:map[string][]string → 查询串;按键字母序排序(确定性输出)
	v := url.Values{}
	v.Add("q", "hello world")
	v.Add("lang", "zh")
	v.Add("tags", "php")
	v.Add("tags", "web")
	fmt.Println(v.Encode())
	fmt.Println(url.Values{"t": []string{"a b&c=d"}}.Encode())
}
输出
lang=zh&q=hello+world&tags=php&tags=web
t=a+b%26c%3Dd

Java v27.0.1

v27.0.1
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // URLEncoder:空格编为 +(form 风格);标准库无“数组展开”,嵌套结构需自行约定
        Map<String, String> data = new LinkedHashMap<>();
        data.put("q", "hello world");
        data.put("lang", "zh");
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> e : data.entrySet()) {
            if (sb.length() > 0) sb.append('&');
            sb.append(URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8))
              .append('=')
              .append(URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8));
        }
        System.out.println(sb);
        System.out.println("t=" + URLEncoder.encode("a b&c=d", StandardCharsets.UTF_8));
    }
}
输出
q=hello+world&lang=zh
t=a+b%26c%3Dd

JavaScript v26.13.1

v26.13.1
// URLSearchParams 构造:对象 → 查询串(保插入序);空格编为 +
const params = new URLSearchParams({ q: "hello world", lang: "zh" });
params.append("tags", "php");
params.append("tags", "web"); // 同名键重复出现(无 PHP 的 tags[0]/tags[1] 下标)
console.log(params.toString());
console.log(new URLSearchParams({ t: "a b&c=d" }).toString());
输出
q=hello+world&lang=zh&tags=php&tags=web
t=a+b%26c%3Dd

PHP v8.6.0

v8.6.0
// http_build_query:数组 → URL 编码查询串(与 parse_str 互逆);空格编为 +(RFC 1738 风格)
$data = ["q" => "hello world", "lang" => "zh", "tags" => ["php", "web"]];
echo http_build_query($data), "\n";
// 数字下标数组自动展开为 tags[0]=...(方括号被编码为 %5B/%5D)
echo http_build_query(["t" => "a b&c=d"]), "\n";
输出
q=hello+world&lang=zh&tags%5B0%5D=php&tags%5B1%5D=web
t=a+b%26c%3Dd

Python v3.15.2

v3.15.2
from urllib.parse import quote, urlencode

# urlencode:字典 → 查询串;quote_via 默认 quote_plus(空格编为 +,与 PHP 一致)
data = {"q": "hello world", "lang": "zh", "tags": ["php", "web"]}
print(urlencode(data, doseq=True))  # doseq:列表展开为同名键重复(无 PHP 的 [0]/[1] 下标)
print(urlencode({"t": "a b&c=d"}))
# 空格编为 %20 的 RFC 3986 风格:quote_via=quote
print(urlencode({"t": "a b&c=d"}, quote_via=quote))
输出
q=hello+world&lang=zh&tags=php&tags=web
t=a+b%26c%3Dd
t=a%20b%26c%3Dd

Rust v1.99.1

v1.99.1
// 标准库无查询串序列化:手写百分号编码(RFC 3986,空格编为 %20)
fn encode_component(s: &str) -> String {
    let mut out = String::new();
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char)
            }
            _ => out.push_str(&format!("%{:02X}", b)),
        }
    }
    out
}

fn main() {
    let data = [("q", "hello world"), ("t", "a b&c=d")];
    let qs: Vec<String> = data
        .iter()
        .map(|(k, v)| format!("{}={}", encode_component(k), encode_component(v)))
        .collect();
    println!("{}", qs.join("&"));
}
输出
q=hello%20world&t=a%20b%26c%3Dd

TypeScript v26.13.1

v26.13.1
// URLSearchParams 构造:对象 → 查询串(保插入序);空格编为 +
const params = new URLSearchParams({ q: "hello world", lang: "zh" });
params.append("tags", "php");
params.append("tags", "web"); // 同名键重复出现(无 PHP 的 tags[0]/tags[1] 下标)
console.log(params.toString());
console.log(new URLSearchParams({ t: "a b&c=d" }).toString());
输出
q=hello+world&lang=zh&tags=php&tags=web
t=a+b%26c%3Dd

语言差异说明

C:无内置——手写 RFC 3986 编码(示例);嵌套结构、值类型需自行设计序列化约定。

C++:同 C 手写;实战 Boost.URL。

C#:Uri.EscapeDataString 是 RFC 3986(空格 %20);老 HttpUtility.UrlEncode(System.Web)才是空格 + 的 form 风格——正是 + 与 %20 历史分歧的两个阵营。

Go:url.Values.Encode 按键字母序排序输出(与 PHP/JS 的插入序不同,但天然确定性);url.Values 本质是 map[string][]string,同名键重复即数组。

Java:URLEncoder.encode 空格编为 +(form 风格);无嵌套数组展开,多层结构要自行约定(常见 tags=php&tags=web 重复键或 JSON)。

JavaScript:new URLSearchParams(对象) 保插入序;数组以同名键重复表达(无 [0]/[1] 下标);空格编为 +。

PHP:默认 PHP_QUERY_RFC1738(空格 +),可传 PHP_QUERY_RFC3986(空格 %20);嵌套数组自动展开为 tags[0]=php(方括号编码为 %5B/%5D,Go/JS/Python 生态普遍不认这种下标,跨语言时建议改用重复键或 JSON);第 3 参 arg_separator 可改分隔符(php.ini 的 arg_separator.output 也可能污染输出)。

Python:urlencode(doseq=True) 列表展开为同名键重复;quote_via 切换 + 与 %20 两种风格;字典保插入序。

Rust:标准库无——示例手写 RFC 3986;实战 url crate(Url::query_pairs_mut)。

TypeScript:同 JavaScript。