Backend Development 4 min read

Using PHP urlencode to Encode URLs and Non-ASCII Characters

This article explains how PHP's urlencode function encodes URLs containing special or non‑ASCII characters, provides example code for both English and Chinese strings, and discusses handling spaces with rawurlencode for more precise encoding.

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

URL encoding is an essential technique for transmitting data on the Internet. When a URL contains special characters (such as spaces, ampersands, etc.) or non‑ASCII characters (such as Chinese, Japanese, etc.), it must be encoded to ensure correct transmission and parsing. In PHP, the built‑in urlencode function can be used to encode URLs.

The urlencode function converts special and non‑ASCII characters in a string into a URL‑safe format that can be parsed and transmitted. Below is a sample code snippet:

<code>&lt;?php
// 要编码的字符串
$str = "Hello World!";

// 使用 "urlencode" 函数对字符串进行URL编码
$encodedStr = urlencode($str);

// 输出编码后的字符串
echo $encodedStr;
?&gt;
</code>

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

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

<code>&lt;?php
// 要编码的字符串
$str = "你好,世界!";

// 使用 "urlencode" 函数对字符串进行URL编码
$encodedStr = urlencode($str);

// 输出编码后的字符串
echo $encodedStr;
?&gt;
</code>

Running this code outputs the URL‑encoded version of the string "你好,世界!": %e4%bd%a0%e5%a5%bd%ef%bc%8c%e4%b8%96%e7%95%8c%ef%bc%81 .

In practical 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 use urlencode to encode parameters and prevent special or non‑ASCII characters from breaking the URL structure.

Note that the urlencode function encodes spaces as a plus sign ( + ) by default. If you need spaces encoded as %20 , you can use the built‑in rawurlencode function instead.

By using PHP's urlencode function, you can easily encode special and non‑ASCII characters in URLs, ensuring correct transmission and parsing. Remember to encode URLs in your PHP programs to improve stability and security.

backendencodingWeb 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.