htmlentities()与htmlspecialchars()
时间:2020-03-05 18:48:25 来源:igfitidea点击:
htmlspecialchars()和htmlentities()有什么区别?我什么时候应该使用其中一个?
解决方案
回答
从有关htmlentities的PHP文档中:
This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
从PHP文档获取htmlspecialchars:
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.
区别在于所编码的是什么。选择是所有(实体)或者减去"特殊"字符的所有内容,例如"&"号,双引号和单引号,小于和大于(特殊字符)。
我更愿意在可能的情况下使用htmlspecialchars。
回答
我们可能要使用一些Unicode字符编码,例如UTF-8和htmlspecialchars。因为不需要在"字符集"中为"所有[适用]字符"生成" HTML实体"(即htmlentities根据文档进行的操作)。
回答
因为:
- 有时我们正在编写XML数据,而不能在XML文件中使用HTML实体。
- 因为htmlentities比htmlspecialchars替换更多字符。这是不必要的,这会使PHP脚本的效率降低,并且所产生的HTML代码的可读性降低。
仅当页面使用ASCII或者LATIN-1等编码而不是UTF-8且我们正在使用与页面不同的编码来处理数据时,才需要使用" htmlentities"。
回答
htmlspecialchars()会进行最少的编码,以确保字符串不会被解析为HTML。与使用htmlentities()绝对对所有具有编码的内容进行编码相比,这将使字符串更具可读性。
回答
可以使用htmlspecialchars:
- 无需编码所有具有等效HTML字符的字符时。如果我们知道页面编码与文本特殊符号匹配,那么为什么要使用" htmlentities"? htmlspecialchars很简单,产生的代码更少,可以发送给客户端。例如:
echo htmlentities('<Il était une fois un être>.'); // Output: <Il était une fois un être>. // ^^^^^^^^ ^^^^^^^ echo htmlspecialchars('<Il était une fois un être>.'); // Output: <Il était une fois un être>. // ^ ^
第二个较短,如果设置了ISO-8859-1字符集,则不会引起任何问题。
- 当不仅要通过浏览器处理数据(以避免解码HTML实体)时,
- 如果输出是XML(请参阅Artefacto的答案)。