doubeng3412 2014-06-18 10:07
浏览 67

PHP。 JSON编码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); 
  • 写回答

1条回答 默认 最新

  • dtgvl48608 2014-06-18 10:09
    关注

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

    评论

报告相同问题?