php dom加载表单并在其中创建元素
我想做的是加载一个表单并在其中创建元素,但我最终得到了如下结果:php dom加载表单并在其中创建元素,php,html,domdocument,Php,Html,Domdocument,我想做的是加载一个表单并在其中创建元素,但我最终得到了如下结果: <form id="form_54" accept-charset="utf-8"></form><input type="text" name="name"> 由于Ghost,功能正确: public function input($name, $attributes = array(), $type = 'text') { $form = $this->doc->get
<form id="form_54" accept-charset="utf-8"></form><input type="text" name="name">
由于Ghost,功能正确:
public function input($name, $attributes = array(), $type = 'text')
{
$form = $this->doc->getElementsByTagName('form')->item(0);
$input = $this->doc->createElement('input');
$input->setAttribute('type', $type);
$input->setAttribute('name', $name);
if(isset($attributes))
{
foreach($attributes as $attr => $val)
{
$input->setAttribute($attr, $val);
}
}
$form->appendChild($input);
$this->doc->appendChild($form);
}
很可能是在父元素而不是表单上追加。首先尝试以表单为目标,然后进行追加
public function input($name, $attributes = array(), $type = 'text')
{
$dom = new DOMDocument();
$dom->loadXML($this->doc->saveHTML());
// target the form
$form = $dom->getElementsByTagName('form')->item(0);
$input = $dom->createElement('input');
$input->setAttribute('type', $type);
$input->setAttribute('name', $name);
if(isset($attributes))
{
foreach($attributes as $attr => $val)
{
$input->setAttribute($attr, $val);
}
}
$form->appendChild($input);
$this->doc->loadXML($form->saveHTML());
}
那么问题出在哪里呢?我已经编辑了这个问题,你在哪里添加
表单
?它是否已在DOM
中?您的解决方案不起作用。但是getElementsByTagName('form')->项(0);你提到的正是我需要的。因此,我在问题中添加了正确的函数。谢谢大家!@jailbird.phoenix噢,是的,我忘了你的对象的实例在->doc
里面,无论如何,很高兴这有帮助
public function input($name, $attributes = array(), $type = 'text')
{
$form = $this->doc->getElementsByTagName('form')->item(0);
$input = $this->doc->createElement('input');
$input->setAttribute('type', $type);
$input->setAttribute('name', $name);
if(isset($attributes))
{
foreach($attributes as $attr => $val)
{
$input->setAttribute($attr, $val);
}
}
$form->appendChild($input);
$this->doc->appendChild($form);
}
public function input($name, $attributes = array(), $type = 'text')
{
$dom = new DOMDocument();
$dom->loadXML($this->doc->saveHTML());
// target the form
$form = $dom->getElementsByTagName('form')->item(0);
$input = $dom->createElement('input');
$input->setAttribute('type', $type);
$input->setAttribute('name', $name);
if(isset($attributes))
{
foreach($attributes as $attr => $val)
{
$input->setAttribute($attr, $val);
}
}
$form->appendChild($input);
$this->doc->loadXML($form->saveHTML());
}