Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Class HtmlTable
- */
- class HtmlTable
- {
- /**
- * Table data array
- *
- * @var
- */
- private $_table = [];
- /**
- * Overall header rows count
- *
- * @var int
- */
- private $_headerRowsCount = 0;
- /**
- * @var array
- */
- private $_currentRowCells = [];
- /**
- * HtmlTable constructor.
- * @param string $w
- * @param bool $class
- */
- public function __construct($w = '100%', $class = false)
- {
- $this->_table[] = "<table style='min-width:{$w};'" . ($class ? " class=\"{$class}\"" : '') . ">";
- }
- /**
- * @param array $headerRows
- * @return $this
- */
- public function writeTableHeader($headerRows = [])
- {
- if ($headerRows) {
- $this->_headerRowsCount = count($headerRows);
- array_push($this->_table, "\t<thead>\r\n\t\t<tr>");
- foreach ($headerRows as $row) {
- array_push($this->_table, "\t\t\t<th>{$row}</th>");
- }
- array_push($this->_table, "\t\t</tr>\n\t</thead>");
- }
- return $this;
- }
- /**
- * @return $this
- */
- public function writeRow()
- {
- if ($this->_currentRowCells != []) {
- $this->closeRow();
- }
- $this->_currentRowCells[] = "\t<tr>";
- return $this;
- }
- /**
- *
- */
- private function closeRow()
- {
- array_push($this->_currentRowCells, "\t</tr>");
- array_push($this->_table, implode("\r\n", $this->_currentRowCells));
- $this->_currentRowCells = [];
- }
- /**
- * @param null $data
- * @return $this
- * @throws Exception
- */
- public function writeCell($data = null)
- {
- if (in_array(count($this->_currentRowCells), range(0, $this->_headerRowsCount)) || $this->_headerRowsCount == 0) {
- $this->_currentRowCells[] = "\t\t<td>$data\n\t\t</td>";
- return $this;
- }
- throw new Exception('Cell is out of bounds');
- }
- /**
- * @return string
- */
- public function getTable()
- {
- $this->closeRow();
- array_push($this->_table, '</table>');
- return implode("\r\n", $this->_table);
- }
- }
- $htmlTableBuilder = (new HtmlTable('100%', 'table table-responsive'))
- ->writeTableHeader(['id', 'name', 'surname', 'salary']);
- $htmlTableBuilder
- ->writeRow()
- ->writeCell(1)
- ->writeCell('Data 1')
- ->writeCell('Data 2')
- ->writeCell('$ 450');
- $htmlTableBuilder
- ->writeRow()
- ->writeCell(2)
- ->writeCell('Data 1')
- ->writeCell('Data 2')
- ->writeCell('$ 275');
- file_put_contents('./html_table.html', $htmlTableBuilder->getTable());
Advertisement
Add Comment
Please, Sign In to add comment