PHP: how to json to encode hindi language in response

I am working with translation API, but here's the problem. I am using JSON in response and when I do json_encode hindi then the output looks like "\ u092f \ u0939 \ u0915 \ u093e \ u0930 \ u0939 \ u0948"

My code is below

$data = array();
$data['hindi'] = 'यह कार है';
$data['english'] = 'This is car';
echo json_encode($data); die;

      

and the answer

{"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"}

      

+3


source to share


4 answers


This is the correct json and when you display it in the browser and / or parse it, it will result in an object with the correct keys and values:



var json_string = '{"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"}',
    json = JSON.parse(json_string);

// or directly:
var json2 = {"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"};

console.log(json_string);
console.log(json);
console.log(json2);

document.write(json_string);
document.write('<br>');
document.write(json.hindi);
document.write('<br>');
document.write(json2.hindi);
      

Run codeHide result


+4


source


If you are using PHP 5.4 or higher, pass the parameter JSON_UNESCAPED_UNICODE

when callingjson_encode

Example:



$data = array();
$data['hindi'] = 'यह कार है';
$data['english'] = 'This is car';
echo json_encode($data, JSON_UNESCAPED_UNICODE);
die;

      

+4


source


Probably the reason is that these characters are not in UTF-8 (I couldn't find them, at least). From PHP documentation on json_encode :

All string data must be encoded in UTF-8 encoding.

This means that he will have to convert it to a "description" of the characters. Don't worry if you decode it again, it will most likely be correct.

0


source


I have a solution to this problem. This works great for me.

$data = array();
$data['hindi'] = base64_encode('यह कार है');
$data['english'] = 'This is car';
$encoded_text=json_encode($data);

      

To get a Hindi piece of data:

$hindi=base64_decode(json_decode($encoded_text)->hindi);

      

0


source







All Articles