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

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

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败