1

I want to encode json, but when I use json_encode function I get not UTF-8 string. I added header header('Content-Type: application/json; charset=utf-8'); and data from database comes good. How I could solve the problem?

My code:

foreach($dbh->query('SELECT Event.name, Event.description, Category.name as category FROM Event, Category WHERE Event.category_id = Category.category_id') as $row) {
                $event['name'] = utf8_encode($row['name']);
                $event['description'] = utf8_encode($row['description']);
                $event['category'] = utf8_encode($row['category']);
                $events[] = $event;
            }


            echo json_encode($events); 
BenG
  • 401
  • 4
  • 7
  • 15

1 Answers1

0

PHP json_encode needs always UTF8 string despite your charset. You must encode all your strings before.

To clarify, you must use utf8_encode on data extracted from your database if they are not already in utf8.

json_encode(array(
    "one" => utf8_encode("super string &éùà"),
    "two" => utf8_encode("super string &éùà")
));

Note : utf8_encode is only applicable from ISO 8859-1. If you are using another charset, see iconv()

Kevin Labécot
  • 2,005
  • 13
  • 25
  • 1
    You should use `utf8_encode` if, **and only if**, your data is currently encoded in ISO 8859-1 (or, for some reason, pure 7-bit ASCII). It is a not a magic "make any string UTF-8" function, as its name unhelpfully implies. – IMSoP Jun 18 '14 at 10:15
  • Updated. I tried with utf8_encode and without. Result the same. – BenG Jun 18 '14 at 10:16
  • What is the output ? An empty json string ? – Kevin Labécot Jun 18 '14 at 10:17
  • No. Like this: Krep\u00c5\u00a1inis – BenG Jun 18 '14 at 10:18
  • 1
    This is normal ! This is unicode escaped chars. See JSON_UNESCAPED_UNICODE (php 5.4) option if you want plain output - http://php.net/manual/en/function.json-encode.php See also this answer for more explaination : http://stackoverflow.com/a/7382317/911718 – Kevin Labécot Jun 18 '14 at 10:21