php DOMDocument: complete transform of form element? wrapping and removing?

血红的双手。 提交于 2019-12-04 18:38:18
Gordon

Since I cannot find a suitable duplicate that shows how to wrap nodes with DOM, here is the solution:

// Setup DOMDocument and XPath
$dom = new DOMDocument;
$dom->loadHTML($form);
$xpath = new DOMXPath($dom);

// Create <DIV> with class attribute name
$div = $dom->createElement('div');
$div->setAttribute('class', 'name');

// Find <input id="s2email"> and remove event attributes
$input = $xpath->query('/html/body/form/input[@id="s2email"]')->item(0);
$input->removeAttribute('onfocus');
$input->removeAttribute('onblur');

// Find <label for="s2email"> and insert new DIV before that
$label = $xpath->query('/html/body/form/label[@for="s2email"]')->item(0);
$label->parentNode->insertBefore($div, $label);

// Move <label> and <input> into the new <div>
$div->appendChild($label);
$div->appendChild($input);

// Echo the <form> outer HTML
echo $dom->saveHTML($dom->getElementsByTagName('form')->item(0));

The above code will produce (live demo):

<form method="post" action="">
    <input type="hidden" name="ip" value="127.0.0.1"><div class="name">
<label for="s2email">Your Email</label><input type="text" name="email" id="s2email" value="email..." size="20">
</div>
    <input type="submit" name="subscribe" value="Subscribe"><input type="submit" name="unsubscribe" value="Unsubscribe">
</form>

Note that in order to pass a node to saveHTML, you need PHP 5.3.6. See

for possible workarounds before that.

The lazy solution would be to use phpQuery or QueryPath which allow for:

print qp($html)
   ->find("*[onfocus], *[onblur]")->removeAttr("onblur")->removeAttr("onfocus")
   ->top()->find("label[for=s2email], input#s2email")->wrapAll("<div class='name'></div>")
   ->top("form")->xml();

Albeit in this case you could use DOMDocument directly. Only the wrapping part would be a bit more elaborate there. You could simpify this if you wrapped the <label> around the <input> instead of using a for= and name= relationship.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!