php 让 json_encode 不转义 html 实体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3346272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getting json_encode to not escape html entities
提问by psychotik
I send json_encodeddata from my PHP server to iPhone app. Strings containing html entities, like '&'are escaped by json_encodeand sent as &.
我将json_encoded数据从我的 PHP 服务器发送到 iPhone 应用程序。包含 html 实体的字符串,例如'&'被转义json_encode并作为&.
I am looking to do one of two things:
我正在做两件事之一:
make
json_encodenot escape html entities. Doc says 'normal' mode shouldn't escape it but it doesn't work for me. Any ideas?make the iPhone app un-escape html entities cheaply. The only way I can think of doing it now involves spinning up a
XML/HTML parserwhich is very expensive. Any cheaper suggestions?
使
json_encode不转义 html 实体。Doc 说“正常”模式不应该逃避它,但它对我不起作用。有任何想法吗?使 iPhone 应用程序以廉价的方式取消转义 html 实体。我现在能想到的唯一方法是启动一个
XML/HTML parser非常昂贵的。有更便宜的推荐吗?
Thanks!
谢谢!
采纳答案by Artefacto
Neither PHP 5.3 nor PHP 5.2 touch the HTML entities.
PHP 5.3 和 PHP 5.2 都没有触及 HTML 实体。
You can testthis with the following code:
您可以使用以下代码对此进行测试:
<?php
header("Content-type: text/plain"); //makes sure entities are not interpreted
$s = 'A string with & ۸ entities';
echo json_encode($s);
You'll see the only thing PHP does is to add double quotes around the string.
您将看到 PHP 所做的唯一一件事就是在字符串周围添加双引号。
回答by bobince
json_encodedoes not do that. You have another component that is doing the HTML encoding.
json_encode不这样做。您有另一个组件正在执行 HTML 编码。
If you use the JSON_HEX_options you can avoid that any <or &characters appear in the output (they'd get converted to \u003Cor similar JS string literal escapes), thus possibly avoiding the problem:
如果您使用这些JSON_HEX_选项,您可以避免任何<或&字符出现在输出中(它们会被转换为\u003C或类似的 JS 字符串文字转义),从而可能避免问题:
json_encode($s, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT)
though this would depend on knowing exactly which characters are being HTML-encoded further downstream. Maybe non-ASCII characters too?
尽管这取决于确切知道哪些字符在下游进行了 HTML 编码。也可能是非 ASCII 字符?
回答by kander
回答by Tom
Going off of Artefacto's answer, I would recommend using this header, it's specifically designed for JSON data instead of just using plain text.
离开 Arteacto 的答案,我建议使用这个标头,它是专门为 JSON 数据设计的,而不仅仅是使用纯文本。
<?php
header('Content-Type: application/json'); //Also makes sure entities are not interpreted
$s = 'A string with & ۸ entities';
echo json_encode($s);
Make sure you check out this post for more specific reasons why to use this content type, What is the correct JSON content type?
请确保您查看这篇文章以了解为什么使用此内容类型的更具体原因,什么是正确的 JSON 内容类型?

