Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP equivalent of javascript JSON.stringify()

As I notice PHP’s json_encode($array) mess things up on diacritics.
If I update my database column type text with javascript-created JSON passed over HTTP, everything looks good. but when I create the JSON into PHP, some characters get encoded weirdly.

I have this array;

$array = ['M-am întîlnit ieri cu','fosta mea profă de matematică'];

$text = implode(",",$array); // this looks good in db
$json = json_encode($array); // this don't and returns error when try to decode later.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Look at the JSON_UNESCAPED_UNICODE flag:

https://www.php.net/function.json-encode

This flag will "encode multibyte Unicode characters literally" according to https://www.php.net/manual/en/json.constants.php.

So you want to do:

json_encode($array, JSON_UNESCAPED_UNICODE);

This will give you the following output:

["M-am întîlnit ieri cu","fosta mea profă de matematică"]

Working example: https://3v4l.org/daETG

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading