CodexBloom - Programming Q&A Platform

How to implement guide with php 8.1 and json_unescaped_unicode not handling multibyte characters correctly

👀 Views: 47 💬 Answers: 1 📅 Created: 2025-06-12
php json multibyte encoding PHP

I'm experiencing a question with PHP 8.1 where the `json_encode` function seems to ignore the `JSON_UNESCAPED_UNICODE` option when encoding strings with multibyte characters. I'm trying to return a JSON response from my API that includes user names in different languages, but instead of getting the expected UTF-8 encoded output, I receive escaped sequences like `\u4f60\u597d` for Chinese characters. Here's the relevant part of my code: ```php $data = [ 'user' => '你好', // This is 'Hello' in Chinese 'status' => 'active' ]; $json = json_encode($data, JSON_UNESCAPED_UNICODE); if ($json === false) { echo 'JSON encoding behavior: ' . json_last_error_msg(); } header('Content-Type: application/json'); echo $json; ``` When I run this code, the output I receive is: `{"user":"\u4f60\u597d","status":"active"}`. I expected it to produce: `{"user":"你好","status":"active"}`. I've checked my PHP configuration and ensured that the `mbstring` extension is enabled. I also tried different combinations of encoding settings, but nothing seems to work. I even created a simple test script that only encodes multibyte characters, and it still outputs the escaped sequences. Is there something I might be missing or a known scenario with PHP 8.1 regarding this? Any insights would be appreciated!