1

I have written this php code for converting umlaut characters (ääää) to use in a json string, but it is not returning the exact result I want.

Code:

mysql_set_charset("ut8");
$size = "ääää";
$d=utf8_encode($size);
echo $de= json_encode($d);

Result:

ääää

Expected result:

ääää

How can I achieve this result?

giorgio
  • 10,111
  • 2
  • 28
  • 41
Sunil Bhawsar
  • 201
  • 3
  • 14
  • Have you tried without the ``utf8_encode``? If your file is saved as UTF8, you do not need to use that function. – Guido Kitzing Dec 02 '15 at 12:16
  • Possible duplicate - http://stackoverflow.com/questions/13602075/problems-with-german-umlauts-in-php-json-encode – Shreyas Dec 02 '15 at 12:16
  • Sidenote: [Do not use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – giorgio Dec 02 '15 at 12:22

2 Answers2

1

You have to set content type json for that by using header and with json_encode use the second parameter ie. JSON_UNESCAPED_UNICODE

    header('Content-Type: application/json; Charset=UTF-8');
    mysql_set_charset("ut8");
    $size = "ääää";
    echo $de= json_encode($size,JSON_UNESCAPED_UNICODE);
NITIN PATEL
  • 460
  • 5
  • 12
  • Although the code may or may not come from a mysql database, the `mysql_set_charset()` function does not do anything usefull here when the string is already stored in a variable. – giorgio Dec 02 '15 at 12:21
  • I've tested your code, the `utf8_encode()` is not needed and will break the code. The header should be removed, as the OP didn't ask for the json to be sent directly to the users browser (it seems that he wants to store it in a database). Just `json_encode($size,JSON_UNESCAPED_UNICODE);` is enough. – giorgio Dec 02 '15 at 12:27
  • yes that was by written by mistake i have edited the code – NITIN PATEL Dec 02 '15 at 12:30
  • Its working on the system after removing $d=utf8_encode($size); and $size to be added in the json_encode string – Harshit Sethi Dec 02 '15 at 12:30
  • yeah but remove the `header()` and `mysql_set_charset()` functions from your answer as well. Then it's correct and down to the point, and you'll earn a +1 from me ;) – giorgio Dec 02 '15 at 12:33
  • I have tried your approach giorgio but not working it is giving the different result – Harshit Sethi Dec 02 '15 at 12:37
0

Here is a useful function for anyone who stumbles into this issue in the future: php function

CodeSlave
  • 457
  • 6
  • 17