How to use Umlauts from PHP in Javascript
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 ne开发者_StackOverflow中文版ed to walk through the $results
array and encode each value somehow? Or something completely different?
json_encode
Docs 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 iconv
Docs or the mb_string
library, both can do that:
$utf8 = iconv($in = 'LATIN-1', $out = 'UTF-8', $latin1);
精彩评论