0

I've been trying to get a chat log from my database, but for some reason characters like ü get converted into \u00. How do I solve this?

Database is already set to UTF-8, so is the header.

Code:

$sql = $db->query("SELECT * FROM `messages` ORDER BY `id` DESC LIMIT 50"); // lol
$row = $sql->fetchAll(PDO::FETCH_ASSOC);    

$messages = array();
foreach($row as $value){
    array_push($messages, $value);
}

exit(json_encode($messages));   

PDO Connection,

$db = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
Martijn Ebbens
  • 253
  • 3
  • 15

1 Answers1

0

Try adding the option JSON_UNESCAPED_UNICODE to your json_encode.

json_encode($row, JSON_UNESCAPED_UNICODE)

The difference:

php > $row = ['ü'];
php > var_dump(json_encode($row));
string(10) "["\u00fc"]"
php > var_dump(json_encode($row, JSON_UNESCAPED_UNICODE));
string(6) "["ü"]"

Demo: https://eval.in/898350

See this answer about security implications; https://stackoverflow.com/a/16584167/5873008

alistaircol
  • 1,433
  • 12
  • 22