Backend Development 4 min read

Using PHP urlencode to Encode URLs and Non-ASCII Characters

This article explains how PHP's urlencode function encodes special and non‑ASCII characters in URLs, provides example code for both English and Chinese strings, and discusses practical usage considerations such as space handling and when to use rawurlencode.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP urlencode to Encode URLs and Non-ASCII Characters

URL encoding is essential for transmitting data on the internet. When a URL contains special characters (e.g., space, ampersand) or non‑ASCII characters (e.g., Chinese, Japanese), the URL must be encoded to ensure correct transmission and parsing. In PHP, the built‑in function urlencode can be used for this purpose.

The urlencode function converts special and non‑ASCII characters in a string to a URL‑safe form that can be parsed and transmitted. Below is an example code:

// 要编码的字符串
$str = "Hello World!";
// 使用 "urlencode" 函数对字符串进行URL编码
$encodedStr = urlencode($str);
// 输出编码后的字符串
echo $encodedStr;
?>

Running the above code outputs the URL‑encoded version of "Hello World!" as %48%65%6c%6c%6f%20%57%6f%72%6c%64%21 .

When the URL contains non‑ASCII characters, such as Chinese, the same urlencode function can be used. Below is an example with Chinese characters:

// 要编码的字符串
$str = "你好,世界!";
// 使用 "urlencode" 函数对字符串进行URL编码
$encodedStr = urlencode($str);
// 输出编码后的字符串
echo $encodedStr;
?>

Running this code outputs the URL‑encoded version of "你好,世界!" 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 urlencode encodes spaces as “+” 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, you can easily encode special and non‑ASCII characters in URLs, ensuring proper transmission and parsing. Remember to encode URLs in your PHP programs to improve stability and security.

backend developmentweb developmentPHPURL encodingurlencode
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.