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...
Using the standard method when reading from MySQL:
The encoding can be done using the following:
The
if is_null
has to be included so that null fields (e.g., DateTime fields) remain null in the output.The
$data
(in my case) is an array with text values as ISO-8859-1. The trick below prepares$data
to be used withjson_encode
.This function will cast the correct data type for the JSON output and utf8_encode the strings.
As Greg mentioned, I had to encode åäö to
UTF-8
. But I did't use iconv or mbstring. When Iutf8_encode()
all values before putting the values to thearray
the problem was solved.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 withjson_encode
. Later after runningjson_decode
, you can decode the string withbase64_decode
, you'll get the original data unmodified.JSON defines strings as Unicode!
JSON Definition
You have to encode you ISO to UTF-8