problems with german umlauts in php json_encode

I'm getting troubles with data from a database containing german umlauts. Basically, whenever I receive a data containing umlauts, it is a black square with an interrogation mark. I solved this by putting

mysql_query ('SET NAMES utf8')

before the query.

The problem is, as soon as I use json_encode(...) on a result of a query, the value containing an umlaut gets null. I can see this by calling the php-file directly in the browser. Are there other solution than replacing this characters before encoding to JSON and decoding it in JS?


Solution 1:

Check out this pretty elegant solution mentioned here:

json_encode( $json_full, JSON_UNESCAPED_UNICODE );

If the problem isn't anywhere else in your code this should fix it.

Edit: Umlaut problems can be caused by a variety of sources like the charset of your HTML document, the database format or some previous php functions your strings run through (You should definitely look into multibyte functions when having problems with umlauts).

These problems tend to be the pretty annoying because they are hard to track in most cases (altough this isn't as bad as it was a few years ago). The function above fixes – as asked – umlaut problems with json_encode … but there is a good chance that the problem is caused by a different part of your application and not this specific function.

Solution 2:

I know this might be old but here a better solution:

Define the document type with utf-8 charset:

<?php header('Content-Type: application/json; charset=utf-8'); ?>

Make sure that all content is utf_encoded. JSON works only with utf-8!

function encode_items(&$item, $key)
{
    $item = utf8_encode($item);
}
array_walk_recursive($rows, 'encode_items');

Hope this helps someone.