The code makes no sense. DOMNode does not have a constructor. It should not be created at all. You must create specific node types through DOMDocument in order to bind them to the document.
Assuming that you want to add the entire H2 element using binding, follow these steps:
libxml_use_internal_errors(true); $DOM = new DOMDocument(); $DOM->loadHTML($htmlString); $DOM->preserveWhiteSpace = false; foreach ($DOM->getElementsByTagName('h2') as $h2) { $a = $DOM->createElement('a'); $a->setAttribute('name', $h2->nodeValue); $h2->parentNode->insertBefore($a, $h2); } $DOM->formatOutput = true; echo $DOM->saveHTML();
Demo http://codepad.org/N0dPcLwT
To wrap H2 elements in element A, just do the same and add
$a->appendChild($h2);
Demo http://codepad.org/w7Hi0Bmz
source share