json_encode in PHP converts Cyrillic in \u041D codes

Actually a subject. How to fix this behavior?
October 3rd 19 at 03:42
3 answers
October 3rd 19 at 03:44
json_encode($str, JSON_UNESCAPED_UNICODE);
only starting from 5.4.0, thank you. - Harvey.Gra commented on October 3rd 19 at 03:47
In some earlier versions of PHP (where JSON_UNESCAPED_UNICODE yet) works well that's the thing:

prepareUTF8 function($matches){
 return json_decode('"\u'.$matches[1].'"');
}

And use it with the JSON output like this:

echo preg_replace_callback('/\\\u([01-9a-fA-F]{4})/', 'prepareUTF8',
 json_encode( /* ...and here are placed the data to be encoded... */ )
);
- Ibrahim42 commented on October 3rd 19 at 03:50
nfedyk a sense to use PHP 5.3 now? 5.4 have long been stable, has more features and better performance. - toni commented on October 3rd 19 at 03:53
OnYourLips, the point is that a lot of servers admins — little, and the update is not scheduled. and to maintain multibit encoding is necessary now. The project architect didn't know that it's a problem, and I did not know until he came to her.

The solution which I use:

foreach ($input as &$val) {
 $val = preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
 function($matches) {
 return mb_convert_encoding(pack('H*', $matches[1]), 'UTF-8', 'UTF-16');
 }, $val);
}
- Harvey.Gra commented on October 3rd 19 at 03:56
OnYourLips, I have on some servers is still 5.2. :)
However in fairness it is those servers which are scheduled a maximum of one month to clean up, but nevertheless — it works, security is not threatened, why change that? - priscilla_Reynol commented on October 3rd 19 at 03:59
Well, PHP 5.2 upgrade is still necessary, because the support for this branch is terminated (which the security is still threatened): php.net/eol.php - Lenny_Schill commented on October 3rd 19 at 04:02
October 3rd 19 at 03:46
Actually, the "fix" does not necessarily (although in terms of perfectionism I understand you well). It's a legitimate JS-rows, the browser displays correctly. The amount of data, however, more. But, on the other hand, Gzip-compressed, this factor is minimized. ;-)

You can still do so:

$json = defined('JSON_UNESCAPED_UNICODE')
 ? json_encode($data, JSON_UNESCAPED_UNICODE)
 : json_encode($data);

Then in the latest versions of PHP JSON code to be optimal in size, and in older — only slightly less optimal.
October 3rd 19 at 03:48
For PHP 5.3 and below, you
preg_replace_callback('/\\\u([01-9a-fA-F]{4})/', 'prepareUTF8', json_encode($array))

Find more questions by tags PHPUnicode