Current Location: Home> Latest Articles> Complete Guide to Fix PHP Chinese Character Encoding Issues

Complete Guide to Fix PHP Chinese Character Encoding Issues

M66 2025-11-06

Causes of PHP Chinese Character Garbling

Chinese character garbling often occurs in PHP development due to inconsistent character encodings. Common causes include files not being saved in UTF-8, database connections missing UTF-8 settings, or HTML pages lacking proper charset declarations. To fully fix the issue, ensure consistent UTF-8 encoding across the entire project.

Set File Encoding

First, make sure your PHP file is saved with UTF-8 (without BOM) encoding. In your editor, save the file as UTF-8, and use the header function to specify the output encoding at the beginning of the file:

<?php
header('Content-Type: text/html; charset=utf-8');
?>

Set Database Connection Charset

If your PHP script connects to a MySQL database, set the connection charset to UTF-8 right after connecting. This ensures proper handling of Chinese characters in database read/write operations:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
?>

Set HTML Page Encoding

When outputting web pages, define the page charset as UTF-8 in the HTML head section. This helps browsers correctly interpret the page content:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Chinese Encoding Issue</title>
</head>
<body>
<?php
echo "Hello, world!";
?>
</body>
</html>

Use mb_convert_encoding Function

If your PHP script handles strings with mixed or unknown encodings, use the mb_convert_encoding function to convert them to UTF-8:

<?php
$str = "Chinese Garbled";
$str_utf8 = mb_convert_encoding($str, "UTF-8");
echo $str_utf8;
?>

Set HTTP Header Encoding

Before outputting any content, use the header function to set the HTTP header and specify UTF-8 encoding. This ensures the correct content type and encoding are sent to the browser:

<?php
header('Content-Type: text/html; charset=utf-8');
echo "Hello, world!";
?>

Conclusion

The key to solving PHP Chinese character garbling issues is to maintain consistency across all levels — file encoding, database connection, web page, and HTTP headers — by using UTF-8. Once all components use the same encoding, PHP will display Chinese characters correctly and smoothly, ensuring better compatibility and user experience.