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

    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算