Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 410
Valentino Ru Avatar asked Nov 28 '12 09:11

Valentino Ru


3 Answers

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.

like image 78
GDY Avatar answered Nov 10 '22 09:11

GDY


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.

like image 15
mffap Avatar answered Nov 10 '22 10:11

mffap


You probably just want to show the texts somehow in the browser, so one option would be to change the umlauts to HTML entities by using htmlentities().

The following test worked for me:

<?php
    $test = array( 'bla' => 'äöü' );
    $test['bla'] = htmlentities( $test['bla'] );

    echo json_encode( $test );
?>
like image 6
Sirko Avatar answered Nov 10 '22 10:11

Sirko