温馨提示×

php table的样式如何自定义

PHP
小樊
81
2024-09-09 02:10:51
栏目: 编程语言

要自定义 PHP 表格的样式,您需要使用 HTML 和 CSS。以下是一个简单的示例,说明如何创建一个带有自定义样式的 PHP 表格:

  1. 首先,创建一个包含数据的 PHP 数组:
<?php
$data = [
    ['name' => 'John', 'age' => 28, 'city' => 'New York'],
    ['name' => 'Jane', 'age' => 24, 'city' => 'San Francisco'],
    ['name' => 'Mike', 'age' => 35, 'city' => 'Los Angeles'],
];
?>
  1. 接下来,使用 HTML 和 PHP 输出表格:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom PHP Table</title>
    <style>
        /* 自定义表格样式 */
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
    </style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>City</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($data as $row): ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['name']); ?></td>
                    <td><?php echo htmlspecialchars($row['age']); ?></td>
                    <td><?php echo htmlspecialchars($row['city']); ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</body>
</html>

在上面的示例中,我们首先使用 HTML 和 CSS 定义了表格的自定义样式。然后,我们使用 PHP 输出表格的数据。htmlspecialchars() 函数用于防止 XSS 攻击,确保数据的安全性。

0