views:

846

answers:

4

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...

+4  A: 

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.

Greg
A: 

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.

Johan
A: 

Using the standard method when reading from MySql: $resultArray = array(); while($obj = MySQL_fetch_object($res)) { $resultArray[] = $obj; } $result = json_encode($resultArray);

The encoding can be done using the following: $resultArray = array(); while($obj = MySQL_fetch_object($res)) { foreach($obj as $key => $value) { if (!is_null($value)) { $obj->$key = utf8_encode($value); } } $resultArray[] = $obj; } $result = json_encode($resultArray);

The "if is_null" has to be included to get fields (eg. DateTime fields) staying null.

BennyBechDk
A: 

JSON defines strings as Unicode!

JSON Definition

You have to encode you ISO to UTF-8

Bernd Ott