How to get json_encode() to work with ISO-8859-1 (åäö)
Solution 1
As Greg mentioned, I had to encode åäö to UTF-8
. But I did't use iconv or mbstring. When I utf8_encode()
all values before putting the values to the array
the problem was solved.
Solution 2
It says in the json_encode()
documentation:
This function only works with UTF-8 encoded data.
You should convert it to utf-8 with iconv or mbstring first.
Solution 3
This function will cast the correct data type for the JSON output and utf8_encode the strings.
/* Change data-type from string to integar or float if required.
* If string detected then utf8_encode() it. */
function cast_data_types ($value) {
if (is_array($value)) {
$value = array_map('cast_data_types',$value);
return $value;
}
if (is_numeric($value)) {
if(strpos('.', $value)===false) return (float)$value;
return (int) $value;
}
return utf8_encode((string)$value);
}
json_encode (cast_data_types($data));
Solution 4
JSON defines strings as Unicode!
You have to encode you ISO to UTF-8
Solution 5
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.
Johan
Updated on August 09, 2020Comments
-
Johan over 3 years
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...