user2301515
user2301515

Reputation: 5107

Encoding and decoding in json

If a json data

{"inf": "Väri-väri"} 

is saved like

{"inf": "Vu00e4ri-vu00e4ri"}

How to recover letters õ, ä, ö, ü, etc in whole json with php. utf8_decode, and utf8_encode i tried. Thank you.

Upvotes: 0

Views: 81

Answers (3)

helmbert
helmbert

Reputation: 37934

The problem in your case is not the JSON encoding in itself, but how you store the encoded JSON document. Note how the encoded JSON document actually should look like:

$a = ["inf" => "Väri-väri"];
echo json_encode($a) . "\n";
// prints: {"inf":"V\u00e4ri-v\u00e4ri"}

This is the expected behaviour in PHP and totally consistent with the JSON spec in RFC-7159:

Any character may be escaped. If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF), then it may be represented as a six-character sequence: a reverse solidus, followed by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point. The hexadecimal letters A though F can be upper or lower case. So, for example, a string containing only a single reverse solidus character may be represented as "\u005C".

However, you're losing the \ characters at some point when storing the data. A wild guess is that you're storing these strings in a relational database using SQL and did not escape properly. The first thing I'd suggest is to investigate how you store your data and ensure that backslashes are properly escaped when storing these strings in a database. If stored correctly, json_decode will easily decode the encoded characters back to regular unicode characters.

Alternatively, you can disable this behaviour by passing the JSON_UNESCAPED_UNICODE flag into json_encode:

echo json_encode($a, JSON_UNESCAPED_UNICODE));

Upvotes: 1

skank
skank

Reputation: 91

you have some flag for jsong_encode for get option : http://php.net/manual/en/json.constants.php try

json_encode($myVar,JSON_UNESCAPED_UNICODE)

Upvotes: 1

user4144415
user4144415

Reputation:

Have a look on the php documentation. If you decode the json code, the letters will be recovered.

Upvotes: 0

Related Questions