Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get json_encode() to work with ISO-8859-1 (åäö)

json_encode() wont work for me when I'm using åäö. Why? And how can I get it to work?

The php:

echo json_encode($arr);

The javascript:

var theResponse = JSON.parse(xmlHttp.responseText);

When I alert() the response, and the response contains å, ä or ö, the response is = NULL

Please, help me out...

like image 404
Johan Avatar asked Sep 08 '09 14:09

Johan


People also ask

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

What is json_encode and Json_decode?

JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.

What does json_encode return?

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.

What encoding is JSON?

The default encoding is UTF-8. (in §6) JSON may be represented using UTF-8, UTF-16, or UTF-32. When JSON is written in UTF-8, JSON is 8bit compatible. When JSON is written in UTF-16 or UTF-32, the binary content-transfer-encoding must be used.


2 Answers

Old question, but figured I'd put this here in case someone needs to log data using json_encode but keep the data untouched, intact for inspection later.

You can encode the data raw using base64_encode, then it will work with json_encode. Later after running json_decode, you can decode the string with base64_decode, you'll get the original data unmodified.

like image 150
Michael Butler Avatar answered Sep 29 '22 11:09

Michael Butler


As of PHP 5.4.0:

Convert your strings in your array to into utf-8 using utf8_encode($str) function.

Then json_encode with JSON_UNESCAPED_UNICODE option:

$arr = json_encode($array, JSON_UNESCAPED_UNICODE);

like image 36
George Avatar answered Sep 29 '22 10:09

George