如何在PHP中从MySQL数据库中显示HTML。

7

我遇到了一个问题,无法在mysql表格中显示html标签。我尝试使用addslashes、mysql_real_escape_string和stripslashes来正确查看标签,但是每次通过浏览器查看数据时,它都会显示html的文本。例如:

我在mysql数据库表中有这个内容:

<strong>Test</strong>

在网页中查看时应该显示为:测试

但实际上,它显示为<strong>测试</strong>

我用的 PHP 代码来显示内容是:

<?php

require_once("inc.php"); //This includes the configuration for mysql database

?>
<html>
  <head>
  </head>
  <body>
    <p>
<?php

$conn = mysql_connect(HOST,USER,PASS) or die(mysql_error());
        mysql_select_db(NAME) or die(mysql_error());

$sql = "SELECT * FROM events";
$query = mysql_query($sql);

while($row = mysql_fetch_assoc($query)){
  echo(stripslashes($row['details'])); //The details is what contains the <strong>Test</strong>
}

mysql_close($conn) or die(mysql_error());

?>
    </p>
  </body>
</html>

你使用什么代码来显示数据?另外,根据你的问题,你应该添加PHP作为标签。 - aaaaaa123456789
1
你使用的框架很可能会自动进行输出转义以防止XSS攻击。在我所知道的所有框架中,都有一种简单的方法可以输出未进行转义的字符串。你应该在问题中添加你使用的框架名称。 - Hari
我正在使用PHP来显示数据。 - Vince
1个回答

47

使用htmlspecialchars_decode函数

替换以下行

  echo(stripslashes($row['details'])); //The details is what contains the <strong>Test</strong>

使用

  echo htmlspecialchars_decode(stripslashes($row['details'])); //The details is what contains the <strong>Test</strong>

3
这很有效!为什么不接受这个答案呢?真的很有帮助。 - Harsha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接