Current Location: Home> Latest Articles> Effective Solutions for JSON Chinese Character Encoding Issues in PHP

Effective Solutions for JSON Chinese Character Encoding Issues in PHP

M66 2025-08-02

Overview of JSON Chinese Character Garbling in PHP

During PHP development, JSON is frequently used as a data exchange format. However, developers often face an issue where Chinese characters in the JSON output appear as garbled text. This problem is usually caused by improper encoding settings. In this article, we'll explore several practical methods to resolve this issue.

Set the Correct Response Header

Before outputting JSON data, make sure to set the proper response header using PHP's header function to specify both the content type and character encoding.

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

This tells the browser that the content is in JSON format and encoded in UTF-8, helping to avoid character display issues.

Use json_encode with Parameters

By default, json_encode converts Chinese characters into Unicode escape sequences. To prevent this and preserve readable Chinese text, add the JSON_UNESCAPED_UNICODE flag.

$data = ['name' => 'Zhang San', 'age' => 25];
$json = json_encode($data, JSON_UNESCAPED_UNICODE);

This ensures that Chinese characters are not escaped and will display correctly in the JSON output.

Convert Encoding with mb_convert_encoding

If issues persist despite setting the header and encoding options, you can try using mb_convert_encoding to manually convert the character encoding of the JSON string.

$data = ['name' => 'Li Si', 'age' => 30];
$json = json_encode($data);

// Convert JSON string from UTF-8 to GBK
$json = mb_convert_encoding($json, 'GBK', 'UTF-8');

This approach is particularly useful when output needs to conform to a specific character set like GBK. Adjust the target encoding according to your environment.

Conclusion

Chinese character garbling in JSON output is a common issue in PHP development, but one that can be resolved easily. By setting the correct response headers, using the appropriate json_encode flags, and converting encodings when necessary, you can ensure that Chinese content is displayed accurately. Consistent encoding practices are essential for reliable data representation.

  • Related Tags:

    JSON