PHP DomNode-> insertBefore ()

I am trying to insert nodes into an html string. My goal is to insert an element before each h2 tag.

For this, I use:

$htmlString = "<h2>some html</h2>"; $DOM = new DOMDocument(); $DOM->loadHTML($htmlString); $itemTitles = $DOM->getElementsByTagName('h2'); for($i = 0; $i < $itemTitles->length; $i ++) { $helpNavigatorContents[] = $itemTitles->item($i)->nodeValue; $textBefore = new DOMNode( '<a name="'.$itemTitles->item($i)->nodeValue.'"></a>' ); $itemTitles->item($i)->parentNode->insertBefore( $textBefore, $itemTitles->item($i) ); } $htmlString = $DOM->saveHTML($DOM); 

And here I have a problem with $textBefore . When I declare $textBefore as a DOMText , I can insert the text before the node, but when I try this with the DOMNode , I get the following error ( Demo ):

Warning: DOMNode :: insertBefore (): Failed to get DOMNode

+4
source share
1 answer

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

+9
source

Source: https://habr.com/ru/post/1436825/


All Articles