nisnis
nisnis

Reputation: 49

Convert a JSON into a UTF-8 string

I want to convert a JSON object into a string. when I am using json_encode I get a string but all with hex letters. I want to convert it to a UTF-8. In other words I want to see the characters. How do I do it?

Upvotes: 4

Views: 15016

Answers (4)

Chandresh M
Chandresh M

Reputation: 3828

You can try passing an option to json_encode():

json_encode ( $value, JSON_UNESCAPED_UNICODE );

The JSON_UNESCAPED_UNICODE option is only available in PHP version 5.4.0 and later.

Thanks.

Upvotes: 4

Moe
Moe

Reputation: 71

I was using json_encode to store data such as Arabic Characters in MySQL fields.

It would store the Arabic characters as HEX within the Database like this:

u0644 u063a...

Which is incorrect. You must ensure that you wrap your json_encode with mysql_escape_string().

This will make sure that the data is put in MySQL as:

\u0644\u063a...

Then, when you use json_decode, it converts the HEX strings into UTF-8 and is output correctly.

Upvotes: 7

tawfekov
tawfekov

Reputation: 5122

you are looking exactly for the funcition json_decode it can convert json strings into utf8

here is an example of arabic word

$re = json_encode('لغة عربية'); 
echo $re ; 
$dd = json_decode($re);
echo $dd ; 
die;

it output : "\u0644\u063a\u0629 \u0639\u0631\u0628\u064a\u0629" لغة عربية

more examples here http://php.net/manual/en/function.json-decode.php

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

You can't, in PHP. Besides, the strings will still be the same once you decode them.

Upvotes: 1

Related Questions