Build up html elements in PHP in a Object Oriented way
This package makes it easy to build up html elements in PHP in a Object Oriented way. It allowes you to manipulate the basic html structure as easy and managable as possible. After the html is setup, it can be rendered as a string., (*1)
The package is divided in three parts:, (*2)
The easiest way to use this package is with Composer. Add the following line to your composer.json file:, (*3)
"require": { "boyhagemann/html": "dev-master" }
This package comes is built on a simple Element class. It has attributes and can hold other elements nested as children., (*4)
Starting with a new element is simple, (*5)
use Boyhagemann\Html\Table; $table = new Table;
Change the attributes of an element, (*6)
$table->attr('class', 'fancy-table');
You can insert a new element easy, (*7)
$table->insert($tr = new Tr());
Insert an element with text, (*8)
$tr->insert(new Td('This is a nice text');
You can edit each child element easily, (*9)
$tr->eachChild(function($td, $i) { $td->attr('class', 'my-class') $td->setValue('My value ' . $i); });
With the builder you can build the html and manipulate the structure of the elements., (*10)
You can insert new elements to a parent element, (*11)
use Boyhagemann\Html\Builder; $builder new Builder; $builder->insert(new Table, 'tr');
Register a callback, so you get a fresh instance every time, (*12)
$builder->register('myCustomElement', function() { $element = new Element; $element->setName('thead'); $element->attr('class', 'example-class'); return $element; }
Or register an instance to use the same instance every time, (*13)
$builder->register('myTable', new Table);
Or register a class, (*14)
$builder->register('myTd', 'Your\Html\Td');
Now we can use this element throughout the whole project., (*15)
$builder->register('table', new Table); $table = $builder->resolve('table'); $tr = $builder->resolve('tr'); $td = $builder->resolve('BoyHagemann\Html\Elements\Td');
We can use it to insert elements, (*16)
$builder->insert('myTable', 'myCustomElement', function($thead) { $thead->insert(new Td('Title'); $thead->insert(new Td('Description'); }
Or insert multiple elements and edit their properties, (*17)
$builder->insertMultiple('myTable', 'tr', 5, function($tr) { // You can edit each table row now $tr->attr('class', 'my-row-class'); $tr->insert(new Td('First value'); $tr->insert(new Td('Second value'); });
Render your html table as... html, (*18)
use Boyhagemann\Html\Renderer; $renderer = new Renderer; // The result is a string with valid html $html = $renderer->render($table);