简体   繁体   English

让json_encode不能逃脱html实体

[英]getting json_encode to not escape html entities

I send json_encoded data from my PHP server to iPhone app. 我将json_encoded数据从我的PHP服务器发送到iPhone应用程序。 Strings containing html entities, like '&' are escaped by json_encode and sent as & 包含html实体的字符串,如'&' ,由json_encode转义并作为&发送& .

I am looking to do one of two things: 我期待做两件事之一:

  • make json_encode not escape html entities. 使json_encode不能转义html实体。 Doc says 'normal' mode shouldn't escape it but it doesn't work for me. Doc说'正常'模式不应该逃脱它,但它对我不起作用。 Any ideas? 有任何想法吗?

  • make the iPhone app un-escape html entities cheaply. 使iPhone应用程序廉价地解除html实体。 The only way I can think of doing it now involves spinning up a XML/HTML parser which is very expensive. 我现在想到的唯一方法就是启动一个非常昂贵的XML/HTML parser Any cheaper suggestions? 任何更便宜的建议?

Thanks! 谢谢!

Neither PHP 5.3 nor PHP 5.2 touch the HTML entities. PHP 5.3和PHP 5.2都不会触及HTML实体。

You can test this with the following code: 您可以使用以下代码对此进行测试

<?php
header("Content-type: text/plain"); //makes sure entities are not interpreted
$s = 'A string with &amp; &#x6F8 entities';
echo json_encode($s);

You'll see the only thing PHP does is to add double quotes around the string. 你会看到PHP唯一能做的就是在字符串周围添加双引号。

json_encode does not do that. json_encode没有这样做。 You have another component that is doing the HTML encoding. 您有另一个正在执行HTML编码的组件。

If you use the JSON_HEX_ options you can avoid that any < or & characters appear in the output (they'd get converted to \< or similar JS string literal escapes), thus possibly avoiding the problem: 如果使用JSON_HEX_选项,则可以避免输出中出现任何<&字符(它们将转换为\<或类似的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. 虽然这取决于确切知道哪些字符在下游进行HTML编码。 Maybe non-ASCII characters too? 也许非ASCII字符呢?

Based on the manual it appears that json_encode shouldn't be escaping your entities, unless you explicitly tell it to, in PHP 5.3. 基于手册 ,似乎json_encode不应该转义您的实体,除非您在PHP 5.3中明确告诉它。 Are you perhaps running an older version of PHP? 您是否正在运行旧版本的PHP?

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. 关于Artefacto的回答,我建议使用这个标题,它是专为JSON数据设计的,而不仅仅是使用纯文本。

<?php
header('Content-Type: application/json'); //Also makes sure entities are not interpreted
$s = 'A string with &amp; &#x6F8 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内容类型是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM