php 中提供 htmlspecialchars() 和 nl2br() 等函数,用于将原始文本转换为 html 实体或换行符。这些函数可以在动态生成 html 代码(如可编辑表单、导航栏或图表)或防止 xss 攻击等场景中发挥作用。
PHP 函数返回 HTML 代码的应用场景
PHP 中提供了一些函数,例如 htmlspecialchars()
和 nl2br()
,可将原始文本转换为 HTML 实体或换行符。在某些情况下,需要在 PHP 脚本中动态生成 HTML 代码,这时这些函数便派上用场。
实战案例:创建可编辑的 HTML 表单
考虑以下场景:您有一个 MySQL 数据库,其中存储了员工信息。您需要创建一个动态表单,以允许用户编辑选定员工的详细信息。
<?php // 连接到数据库 $db = new <a style=\'color:#f60; text-decoration:underline;\' href="https://www.php.cn/zt/15713.html" target="_blank">mysql</a>i(\'localhost\', \'root\', \'\', \'employees\'); // 获取待编辑的员工的 ID $employee_id = $_GET[\'id\']; // 准备查询语句 $stmt = $db->prepare(\'SELECT * FROM employees WHERE id = ?\'); $stmt->bind_param(\'i\', $employee_id); $stmt->execute(); // 获取结果集 $result = $stmt->get_result(); $employee = $result->fetch_assoc(); // 使用 htmlspecialchars() 函数防止 XSS 攻击 $name = htmlspecialchars($employee[\'name\']); $email = htmlspecialchars($employee[\'email\']); // 创建表单 echo <<<HTML <form method="post" action="update.php"> <input type="hidden" name="id" value="$employee_id"> <label for="name">姓名:</label><input type="text" name="name" value="$name"> <br> <label for="email">邮件地址:</label><input type="text" name="email" value="$email"> <br> <input type="submit" value="更新"> <input type="reset" value="重置"> </form> HTML; ?>