1

When decoding/encoding a utf8 string using json_encode/json_decode I do not get back the string in the original encoding...

$test = '{"c":"limón"}';

echo $test;                           //=> {"c":"limón"}    
echo json_decode($test)->{"c"};       //=> limón
echo json_encode(json_decode($test)); //=> {"c":"lim\u00f3n"}

How can I encode the string back to its original encoding (utf8)?

1 Answer 1

4

The default behavior of json_encode is to escape all Unicode characters. If your PHP is version 5.4.0 or greater, you can pass JSON_UNESCAPED_UNICODE as the second parameter of json_encode to get the behavior you're expecting. There are numerous hacks to get this behavior in earlier versions, including preprocessing your object to encode Unicode characters as HTML entities, then reversing the transformation afterwards.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.