Current Location: Home> Latest Articles> PHP Chinese Character Encoding Tips: Solving Garbled Characters and Optimizing Encoding Issues

PHP Chinese Character Encoding Tips: Solving Garbled Characters and Optimizing Encoding Issues

M66 2025-07-14

PHP Chinese Character Encoding Tips: Solving Garbled Characters and Optimizing Encoding Issues

In web development, character encoding is a common problem when handling Chinese characters. Improper encoding handling can lead to garbled characters, affecting the user experience. This article will share some common tips for handling Chinese character encoding in PHP to help developers solve these issues.

Setting PHP File Encoding

First, make sure that the PHP file uses UTF-8 encoding to avoid garbled characters caused by inconsistent encodings. Add the following code at the beginning of your PHP file to set the encoding:

<span class="fun">header('Content-Type: text/html; charset=UTF-8');</span>

String Encoding Conversion

When handling data from the frontend, it is often necessary to convert strings between different encodings. For example, if the string from the frontend is in GBK encoding, we can use the following code to convert it to UTF-8:

$gbk_str = '中文字符串';
$utf8_str = iconv('GBK', 'UTF-8', $gbk_str);
echo $utf8_str;

URL Encoding and Decoding

When passing URLs that contain Chinese characters, URL encoding and decoding are required. The following code can be used as an example:

$original_url = 'http://example.com/搜索.php?keyword=中文';
$encoded_url = urlencode($original_url);
echo $encoded_url;
$decoded_url = urldecode($encoded_url);
echo $decoded_url;

Database Storage of Chinese Characters

When storing Chinese characters in the database, ensure the database uses UTF-8 encoding. You can add the following code to set the character set when connecting to the database:

$mysqli = new mysqli('localhost', 'username', 'password', 'dbname');
$mysqli->set_charset('utf8');

Handling JSON Data Output

If you need to output JSON data containing Chinese characters, you can use the JSON_UNESCAPED_UNICODE option to ensure the Chinese characters are not escaped:

$data = ['中文' => '测试'];
echo json_encode($data, JSON_UNESCAPED_UNICODE);

Conclusion

The tips above introduce common methods for handling Chinese character encoding in PHP, including file encoding setup, string encoding conversion, URL encoding, database storage, and JSON data handling. By properly configuring encoding settings, developers can effectively avoid garbled characters, improving the reliability and user experience of websites. We hope these tips will help you handle Chinese character encoding more effectively in PHP development.