我想创建一个使用PHP以编程方式创建HTML表单的表单构建器,但我希望它是面向对象的.这让我看看PHP的DOM扩展,但它似乎在完整的HTML(和XML)文档的概念而不是DOM的部分.
因此,在PHP中是否可以以面向对象的方式创建HTML?例如,我的伪代码可能如下所示:
$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();
解决方法:
您可以使用DOMDocument(需要PHP 5,顺便说一句):
$html = new DOMDocument('1.0','iso-8859-1');
$html->formatOutput = true;
$form = $html->createElement('form');
$fieldset = $html->createElement('fieldset');
$name = $html->createElement('input');
$name->setAttribute('type', 'text');
$name->setAttribute('name', 'name');
$email = $html->createElement('input');
$email->setAttribute('type', 'text');
$email->setAttribute('name', 'email');
$fieldset->appendChild($name);
$fieldset->appendChild($email);
$form->appendChild($fieldset);
$html->appendChild($form);
echo html_entity_decode($html->saveHTML());
哪个输出:
更完整的文件:
class br extends DOMElement {
function __construct() {
parent::__construct('br');
}
}
$page = new DOMDocument();
$page->normalizeDocument();
$page->formatOutput = true;
$html = $page->createElement('html');
$head = $page->createElement('head');
$title = $page->createElement('title');
$body = $page->createElement('body');
$form = $page->createElement('form');
$fieldset = $page->createElement('fieldset');
$name = $page->createElement('input');
$email = $page->createElement('input');
$submit = $page->createElement('input');
$title_text = $page->createTextNode('Page Title Here');
$title->appendChild($title_text);
$head->appendChild($title);
$html->appendChild($head);
$name->setAttribute('type', 'text');
$name->setAttribute('name', 'name');
$email->setAttribute('type', 'text');
$email->setAttribute('name', 'email');
$submit->setAttribute('type','submit');
$submit->setAttribute('value','Submit');
$fieldset->appendChild($page->createTextNode('Name: '));
$fieldset->appendChild($name);
$fieldset->appendChild(new br);
$fieldset->appendChild($page->createTextNode('Email: '));
$fieldset->appendChild($email);
$fieldset->appendChild(new br);
$fieldset->appendChild($submit);
$form->appendChild($fieldset);
$body->appendChild($form);
$html->appendChild($body);
$page->appendChild($html);
echo "\n" . html_entity_decode($page->saveHTML());
哪个输出:
Page Title HereName:Email:
标签:html,php,dom,forms
来源: https://codeday.me/bug/20190726/1539823.html