我有一个关于使用PHP创建HTML表的问题。我喜欢一些库通过使用PHP组件来处理SQL的创建、读取、更新和删除(CRUD)的方式,这些组件可以执行CRUD,而不需要了解任何SQL,而是使用PHP API。
我需要一个工具,我可以用同样的方式创建HTML表。我想只使用PHP语句创建HTML或其他ML表。
谁能建议一个好的工具,用于创建HTML表与PHP?
提前感谢。
确实有这样的工具可以使用PHP开发HTML表单。
作为PHP开发人员,我的首选是PEAR的HTML_Table
。正如文档所说:"[PEAR的]HTML_Table使HTML表的设计变得简单、灵活、可重用和高效。"
使用这个组件很简单,包括表类(从文件),实例化一个新实例,添加一个主体,并开始使用PHP调用向表添加行。
这是一个显示用户姓名、电子邮件和年龄的表格示例。
这个例子假设你已经安装了PEAR
(安装PEAR)和PEAR的HTML_Table。
HTML_Table
<?php require_once 'path/to/pear/HTML/Table.php'; ?>
您可能还需要包括HTML_Common
&PEAR
类也是如此,所以建议在你的PHP include_path
中有PEAR路径。
要处理这个问题以及一般的PEAR类加载,请查看PSR-0标准,它是PEAR类和文件的命名约定。这在使用自动加载器时可能很有用。
类可用后,我们可以创建如下表:
// Instantiating the table. The first argument is the HTML Attributes of the table element
$table = new HTML_Table(array('class' => 'my-table'), null, true);
注意所有参数都是可选的。让我们首先向表中添加header:
// Preparing the header array this will go in <table><thead><tr>[HERE..]</tr></thead></table>
$headerRow = array('Name', 'Email', 'Age');
$header = $table->getHeader();
$header->setAttributes(array('class' => 'header-row')); // sets HTML Attributes of the <thead /> element
$header->addRow($headerRow, null ,'th');
到目前为止,这个表的HTML看起来像这样:
<table class="my-table">
<thead class="header-row">
<tr>
<th>Name</th>
<th>Email</th>
<th>Age</th>
</tr>
</thead>
</table>
让我们添加一个主体和一些行:
// This is array of arrays that will represent the content added to the table as table rows (probably retrieved from DB)
$resultSet = array(
array(
'name' => 'John Doe',
'email' => 'john.doe@example.com',
'age' => 33,
),
array(
'name' => 'Jane Doe',
'email' => 'j.doe@example.com',
'age' => 30,
),
);
// $bodyId is the body identifier used when appending rows to this particular body
$bodyId = $table->addBody(array('class' => 'main-body'));
foreach ($resultSet as $entry) {
$indexResult = array_values($entry); // <-- the array passed to the addRow must be indexed
$table->addRow($indexResult, array (/* attributes */), 'td', true, $bodyId);
// note how we specify the body ID to which we append rows -----------^
// This is useful when working with multiple table bodies (<tbody />).
}
表中多个<tbody />
标签的概念也可以利用表类的addBody()
方法,该方法返回体标识符,以便在稍后添加行时用作引用(参见上面的注释)。
有了这个,显示表格就很容易了:
<?php
echo $table->toHtml();
// or simply
echo $table;
?>
这个例子的HTML内容现在看起来像这样:
<table class="my-table">
<thead class="header-row">
<tr>
<th>Name</th>
<th>Email</th>
<th>Age</th>
</tr>
</thead>
<tbody class="main-body">
<tr>
<td>John Doe</td>
<td>john.doe@example.com</td>
<td>33</td>
</tr>
<tr>
<td>Jane Doe</td>
<td>j.doe@example.com</td>
<td>30</td>
</tr>
</tbody>
</table>
希望这对你有帮助:)
斯托亚。