Escaping JSON apostrophe before PHP's json_encode truncates?

て烟熏妆下的殇ゞ 提交于 2019-11-30 17:03:18

问题


I have a field in a MySQL database (utf8_general_ci) that contains a curly (smart?) apostrophe: Owner’s...

This prints fine with no special handling if I access the PHP page that pulls it from the DB. However, I am trying to access it via a $.getJSON request on another page, so I used PHP's json_encode. It truncates the value so that it reads Owner, then successfully encodes the rest of the data. If I use PHP's utf8_encode on the field before I json_encode, it includes the full value with the encoded to \u0092 which then doesn't print anything on the page, giving me Owners. PHP's htmlentities and htmlspecialchars have no effect.

Looking at the request in Chrome's tools, Owner’s is shown as Owner�s on the $.getJSON page.

Can anyone help me out here? I have read other questions on SO and the web but I cannot find anything that helps and I haven't worked much with JSON.

Thanks for reading.


回答1:


For details: json_encode

Example:

echo json_encode($array, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);



回答2:


Using PHP's utf8_encode() before my json_encode() did indeed stop the data from cutting off after the but it also encoded it to \0092 which did not display (control character). When I used MySQL's SET NAMES utf8 before my query, I did not have to use utf8_encode() at all, and my json was encoded correctly with mapping to \u2019, which displays nicely.

Thanks for the link @Pekka, it helped me narrow down the possibilities.



来源:https://stackoverflow.com/questions/15097518/escaping-json-apostrophe-before-phps-json-encode-truncates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!