htmlspecialchars 没有按预期工作

htmlspecialchars not working as expected

我可能用错了,问题是这样的: 我有 php 代码被回显到页面,如下所示: <?php echo "<h1>" . htmlspecialchars($array['text']) . "</h1>" ?>

该变量以这样的 html 结构从数据库中回显

echo "<h1> Hello </h1>" 这工作正常,但只要我回显 "> text here" 之类的东西,一切都会中断。文本出现在正文的开头,我实际上可以将 JS 注入其中并且......它起作用了。

我不知道我做错了什么,是我使用 htmlspecialchars 错误还是其他地方的问题?

使用以下内容:

htmlspecialchars($string, ENT_COMPAT,'ISO-8859-1');

这使得 htmlspecialchars 使用 ISO-8859-1 编码,我假设您正在使用这种编码。

关于第三个参数,称为encoding,根据htmlspecialchars docs

If omitted, the default value of the encoding varies depending on the PHP version in use. In PHP 5.6 and later, the default_charset configuration option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1.