Current Location: Home> Latest Articles> How to Solve Chinese Character Encoding Issues in PHP JSON Encoding and Decoding?

How to Solve Chinese Character Encoding Issues in PHP JSON Encoding and Decoding?

M66 2025-07-11

Why Chinese Characters Appear Garbled in PHP JSON Encoding and Decoding

When using JSON encoding and decoding in PHP, encountering garbled Chinese characters is a common issue. This is usually caused by inconsistent character encoding between the server and the client. This article will explain how to resolve this problem through character encoding settings and manual encoding conversion.

Solution 1: Set Character Encoding

To ensure consistent character encoding in PHP JSON encoding and decoding, you can set the character encoding in the HTTP headers using the header() function. This helps avoid the problem of Chinese characters being garbled. Here's an example of how to do this:

header('Content-Type: application/json; charset=utf-8');

$data = array(
    'name' => 'Zhang San',
    'age' => 25,
    'city' => 'Beijing'
);

$json = json_encode($data, JSON_UNESCAPED_UNICODE);

echo $json;

In this example, we set the character encoding to UTF-8 in the HTTP header and use the json_encode() function to convert data containing Chinese characters to JSON format. The JSON_UNESCAPED_UNICODE parameter ensures that Chinese characters are not escaped as Unicode.

Solution 2: Manual Encoding Conversion

If character encoding consistency cannot be ensured between the server and the client, you can manually convert the encoding during encoding and decoding to avoid garbled characters. Here's an example of manual encoding conversion:

$data = array(
    'name' => 'Li Si',
    'age' => 30,
    'city' => 'Shanghai'
);

// Manually convert encoding during encoding
$json = json_encode($data, JSON_UNESCAPED_UNICODE);
$json = mb_convert_encoding($json, 'UTF-8', 'UTF-8');

// Manually convert encoding during decoding
$json = mb_convert_encoding($json, 'UTF-8', 'UTF-8');
$data = json_decode($json, true);

var_dump($data);

In this code, we use the mb_convert_encoding() function to ensure consistent encoding, which helps to avoid garbled Chinese characters.

Conclusion

To solve the issue of garbled Chinese characters in PHP JSON encoding and decoding, you can either set the character encoding or manually convert the encoding. Ensuring consistency between the server and client character encodings is key to avoiding these issues.

We hope that the solutions provided in this article can help you solve the Chinese character encoding problems in PHP JSON encoding and decoding. If you have any further questions, feel free to leave a comment.