简体   繁体   中英

PHP. JSON encode utf-8

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); 

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM