I’m wanting to create a form builder that creates HTML forms programmatically with PHP, but I’m wanting it to be object-orientated. This lead me to looking at PHP’s DOM extension, but it seems to work on the concept of full HTML (and XML) documents rather than portions of the DOM.
Therefore, is it possible in PHP to create HTML in an object-orientated way? For example, my pseudo-code may look as follows:
<?php
$form = new HTMLElement('form', array('method' => 'post', 'action' => 'contact.php'));
$fieldset = $form->addElement(new HTMLElement('fieldset'));
$fieldset->addElement(new HTMLElement('input', array(
'type' => 'text',
'name' => 'name'
)));
$fieldset->addElement(new HTMLElement('input', array(
'type' => 'email',
'name' => 'email'
)));
// and so on...
echo $form->asHTML();
You can use
DOMDocument(requires PHP 5, btw):http://codepad.org/sK0j6zD3
Which outputs:
A more complete document:
http://codepad.org/uRNoW3nN
Which outputs: