guer/chtmltable
HTML表格生成器
Requires
- php: >=5.4
This package is not auto-updated.
Last update: 2024-09-15 01:07:17 UTC
README
CHTMLTable
简介
CHTMLTable 是一个PHP类,用于使用数据对象数组生成HTML表格。数据对象数组的一个例子是从MySQL数据库中获取数据时使用PDO::FETCH_OBJ获取样式。
它可以与Anax MVC一起使用,但不依赖于它。它可以包含在任何其他项目中。
如何安装
要安装包,将以下行添加到您的 composer.json
文件中
"require": {
"guer/chtmltable": "dev-master"
}
如果使用Anax-MVC框架,请将 webroot/table-anax-mvc.php
文件和 webroot/css/html-table.css
文件复制到Anax-MVC webroot目录中的每个文件夹
如何使用
将数据传递到表格中
要在表格中显示值,HTMLTable 使用数据对象数组。每个键代表一个列,相应的值作为表值。
$data = [
[0] => stdClass Object
(
[Column1] => Table Cell 1
[Column2] => Table Cell 2
[Column3] => Table Cell 3
[Column4] => Table Cell 4
[Column5] => Table Cell 5
)
[1] => stdClass Object
(
[Column1] => Table Cell 6
[Column2] => Table Cell 7
[Column3] => Table Cell 8
[Column4] => Table Cell 9
[Column5] => Table Cell 10
)
];
可选元素
表格规范
要设置表格的 CSS id/class 和 标题,请使用表格规范数组。
$tableSpecification = [
'id' => 'test-table',
'class' => 'test-table',
'caption' => 'The table'
];
如果没有设置CSS id或class,则默认id为 "html-table"。
列规范
可以为列设置多个规范。要设置列规范,请使用关联列规范数组。
$columnSpecification = [
$Column1 => [
],
$Column3 => [
'title' => 'Table Header 2',
],
$Column2 => [
'title' => 'Table Header 3',
'function' => function($link) {
return '<a href="https://www.google.se">' . htmlentities($link, null, 'UTF-8') . '</a>';
}
],
$object1 => [
'title' => 'Table Header 4',
'function' => function($object) {
return htmlentities($object->Column4, null, 'UTF-8');
}
],
$Column5 => [
'title' => 'Table Header 5',
'function' => function($isPresent) {
return empty($isPresent) ? 'Not present' : 'Present';
}
],
'tablefoot1' => [
'type' => 'footer',
'colspan' => '4',
'value' => 'Footer Cell 1',
],
'tablefoot2' => [
'type' => 'footer',
'function' => function() {
return '<a href="https://www.google.se">Link</a>';
}
],
];
在列规范中,可以确定表格中的列数及其设置。列规范设置列数及其在表格中的显示顺序。列规范从上到下对应于表格中的从左到右。
要从数据对象中获取值,列规范中的键名必须与数据对象中的键名对应。例如,列规范中的 Column1 键从数据对象中获取键为 Column1 的值。
要获取整个数据对象,列规范中的键名必须以 object(不区分大小写)开头,例如 object、object1 等。如果两个或多个列想要获取数据对象,则键名必须是唯一的。不能使用名称 object1 两次或更多。注意!仅当与定义的函数结合使用时,才能获取数据对象。
如果没有设置 标题,CHTMLTable 使用第一个对象中键的名称作为表标题的名称。
可以使用 函数 来进行更高级的列设置。CHTMLTable 使用 call_user_func 函数从匿名函数获取设置。以下示例显示了如何向列中的所有单元格添加HTML标签,以创建链接,以及根据单元格的值是否包含在输入数组(data)中返回 '不存在' 或 '存在' 的函数。也可以获取以 "object" 开头的键名的对象。注意!CHTMLTable 在使用函数时不会使用 htmlentities() 函数。必须在指定的函数中添加对有害数据的保护。
要添加 页脚,请使用 type 标签并将值设置为 'footer'。如果没有添加类型,则设置被视为列设置。如果只想在页脚中添加简单值,请使用 'value' 标签。否则,使用函数标签进行更高级的设置。对于页脚,还可以设置 'colspan' 标签以跨足页面行中的列。
创建并获取HTML表格
$table = new \Guer\HTMLTable\CHTMLTable();
$table = $table->create($tableSpecification, $data, columnSpecification);
$table->getHTMLTable();
要生成一个未指定格式的表格,只需排除表格规格。数据将根据数据对象中的键的数量以列的形式呈现。列标题是数据对象中键的名称。CHTMLTable 使用 htmlentities() 函数在表格单元格中显示数据。
$table = $table->create([], $data, []);
$table->getHTMLTable();
许可
此软件是免费软件,并携带 MIT 许可证。