1

I have a MySQL database that contains German Umlauts (ä, ü, ö, etc). The database fields are all encoded latin1_german1_c (if that matters).

From that database I create a json object that I use with javascript. However each value that contains one of those Umlauts gets set to null right from the get go via:

var json = <?php echo json_encode($results);?>;

then:

>>> console.log(json[0].name)
null

Do I need to encode my document somehow differently? Do I need to walk through the $results array and encode each value somehow? Or something completely different?

2
  • What does the generated JS code look like, from your browser's view-source? Commented Sep 27, 2011 at 21:06
  • If you do a "view source" on what gets delivered to the browser, what do you see where you're expecting the umlaut? The short version here is that you need to make sure that the encoding you're telling the browser you're using (UTF-8, Windows-1252, etc.) matches what PHP is outputting. Worth reading if you haven't already: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) This doesn't only relate to the JavaScript on the page; it relates to the text as well. Commented Sep 27, 2011 at 21:07

1 Answer 1

3

json_encodeDocs expects strings to be utf-8 encoded, not latin-1 encoded - that's why the values get reset to NULL (unset).

You need to re-encode the strings from latin-1 to utf-8 before you use them with json_encode. Look for iconvDocs or the mb_string library, both can do that:

$utf8 = iconv($in = 'LATIN-1', $out = 'UTF-8', $latin1);
Sign up to request clarification or add additional context in comments.

2 Comments

Hakre, thank you very much for the reply. I tried this but it doesn't seem to take on the php-level. $results[0]["name"] is a string that I get from my db that has an Umlaut in it. So I tried this: echo $weirdstring = $results[0]["name"]."\n"; print_r(json_encode(iconv("LATIN-1", "UTF-8//TRANSLIT", $weirdstring))); this outputs: Mörseburg-Baumhauer false Sorry, I seem to be doing something wrong? Thanks for your help!!
Well that looks working, doesn't it? (you can strip the //TRANSLIT, that's bogus). Don't forget to encode each latin-1 string in the array and then json_encode the array, not a single string only. I linked the functions to the manual, so you can learn more about them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.