問題場景:URL path 包含中文(如 https://example.com/搜索/關鍵詞),直接用 file_get_contents/cURL/wget 請求會返回 404。瀏覽器自動編碼,但伺服端原始請求需手動處理。
function urlConvert($url) {
$pathArr = array();
$modules = parse_url($url);
$path = $modules['path'];
$pathSplit = explode('/', $path);
foreach ($pathSplit as $row) {
$pathArr[] = rawurlencode($row); // 關鍵:逐段編碼
}
$urlNew = $modules['scheme'] . "://" . $modules['host'] . implode('/', $pathArr);
return $urlNew;
}
parse_url() 解析 URL 結構,提取 scheme、host、pathexplode('/', $path) 將 path 拆分為段落(保留層級結構)rawurlencode() **嚴格遵循 RFC 3986**,空格編為 %20(而非 +),適合 path 編碼implode('/', ...) 重組 path,保持目錄結構parse_url 返回的 query 部分),查詢參數編碼邏輯不同| 場景 | 是否適用 | 說明 |
|---|---|---|
| Path 含中文/特殊字符 | ✅ | 核心解決場景 |
| Query 參數含中文 | ❌ | 需用 http_build_query() 處理 query 部分 |
| 完整 URL 含中文域名 | ❌ | 需 Punycode 編碼 (idn_to_ascii()) |
| Fragment (#錨點) 含中文 | ❌ | 瀏覽器端處理,伺服端不接收 |
rawurlencode() 後再拼裝parse_url 再重組,防注入league/uri、guzzlehttp/psr7)替代手工拼裝