dph23577 2013-07-03 13:40
浏览 38
已采纳

带有PHP的重音字母:htmlentities和json_encode

In my PHP webservice I have to return some arrays containing strings with accented letters in JSON format (I parse them in my client app with JS).

But the htmlentities function replaces the strings containing accented letters with empty strings! If I don't use htmlentities, I get an error on json_encode.

$a = array('key' => 'èàìòù');
foreach ($a as $k => $v)
    $a[$k] = htmlentities($v, ENT_QUOTES | ENT_HTML5, 'UTF-8');

json_encode($a);

I also tried the ENT_COMPAT option, but I get only empty values.

Note that if I print my array with print_r before htmlentities, the content is ok.

More information:

Every file is in UTF-8 w/o BOM format (saved with Notepad++). I already tried to add the headers to set UTF-8 in my PHP and HTML. The DB table is in utf8_unicode_ci format.

Versions: PHP 5.3.3, MySQL 5.5.30-1.

Thank you for your help!

  • 写回答

1条回答 默认 最新

  • dsunj08246 2013-07-03 13:52
    关注

    You're not specifying which error you are getting in json_encode(), but my suspicion is that your incoming data is not UTF-8 encoded, which will break both the unnecessary htmlentities() call (which you are instructing to expect UTF-8 data) and json_encode() (because that function requires all input data to be UTF-8).

    Make sure the data you are encoding is actually UTF-8 encoded. You won't be needing htmlentites() at all then.

    You're not saying where the data comes from, but if it's from a database, the connection sometimes needs to be explicitly set to UTF-8. See UTF-8 all the way through

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题