Using PHP urlencode to Encode Special and Non-ASCII Characters in URLs
This article explains how PHP's urlencode function converts special and non‑ASCII characters into URL‑safe representations, provides example code for English and Chinese strings, and discusses practical usage, space handling, and the alternative rawurlencode function for precise encoding.
URL encoding is an essential technology for transmitting data over the Internet. When a URL contains special characters (e.g., spaces, ampersand) or non‑ASCII characters (e.g., Chinese, Japanese), the URL must be encoded to ensure correct transmission and parsing. In PHP, you can use the built‑in function "urlencode" to encode URLs.
The "urlencode" function converts special characters and non‑ASCII characters in a string into a URL‑safe form that can be parsed and transmitted. Below is an example code:
<?php
// 要编码的字符串
$str
=
"Hello World!"
;
// 使用
"urlencode"
函数对字符串进行URL编码
$encodedStr
= urlencode(
$str
);
// 输出编码后的字符串
echo
$encodedStr
;
?>Running the above code will output the URL‑encoded version of the string "Hello World!" as "%48%65%6c%6c%6f%20%57%6f%72%6c%64%21".
When a URL contains non‑ASCII characters, such as Chinese characters, you can also use the "urlencode" function to encode them. Below is an example with Chinese characters:
<?php
// 要编码的字符串
$str
=
"你好,世界!"
;
// 使用
"urlencode"
函数对字符串进行URL编码
$encodedStr
= urlencode(
$str
);
// 输出编码后的字符串
echo
$encodedStr
;
?>Running this code will output the URL‑encoded version of the string "你好,世界!" as "%e4%bd%a0%e5%a5%bd%ef%bc%8c%e4%b8%96%e7%95%8c%ef%bc%81".
In real applications, URL encoding is commonly used to pass parameters to a server, ensuring data integrity and correctness. For example, when sending data with a GET request, you can encode parameters with "urlencode" to prevent special or non‑ASCII characters from breaking the URL structure.
Note that the "urlencode" function encodes spaces as a "+" sign by default. If you need spaces encoded as "%20", you can use the built‑in function "rawurlencode".
In summary, by using PHP's "urlencode" function, we can easily encode special and non‑ASCII characters in URLs to ensure correct transmission and parsing. Remember to encode URLs in PHP programs to improve stability and security.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.