Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to json encode of hindi language in response

Tags:

json

php

hindi

I am working with a translation API but here is an issue. I am using JSON in response and when I do json_encode of Hindi then the out is like "\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948"

My code is given below

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

and the response is

{"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"}
like image 990
vikujangid Avatar asked May 12 '15 09:05

vikujangid


2 Answers

If you are running PHP 5.4 or greater, pass the JSON_UNESCAPED_UNICODEparameter when calling json_encode

Example:

$data = array();
$data['hindi'] = 'यह कार है';
$data['english'] = 'This is car';
echo json_encode($data, JSON_UNESCAPED_UNICODE);
die;
like image 89
ollierexx Avatar answered Nov 16 '22 05:11

ollierexx


This is 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);
like image 34
jeroen Avatar answered Nov 16 '22 04:11

jeroen