Throw a "DOMException" exception with the message "Hierarchy request failed"

I get an error when replacing or adding a child to a node.

It is required:

I want to change this to ..

<?xml version="1.0"?> <contacts> <person>Adam</person> <person>Eva</person> <person>John</person> <person>Thomas</person> </contacts> 

like this

 <?xml version="1.0"?> <contacts> <person>Adam</person> <p> <person>Eva</person> </p> <person>John</person> <person>Thomas</person> </contacts> 

mistake

Fatal error: throw a "DOMException" exception with the message "Hierarchy request failed"

my code

 function changeTagName($changeble) { for ($index = 0; $index < count($changeble); $index++) { $new = $xmlDoc->createElement("p"); $new ->setAttribute("channel", "wp.com"); $new ->appendChild($changeble[$index]); $old = $changeble[$index]; $result = $old->parentNode->replaceChild($new , $old); } } 
+7
source share
1 answer

An error requesting a hierarchy of errors with a DOMDocument in PHP means that you are trying to move the node to itself. Compare this to the snake in the following figure:

Snake eats itself

Similarly with your node. You move the node to yourself. This means that at the moment when you want to replace a person with a paragraph, the person is already a child of this paragraph.

The appendChild () method effectively moves a person from the DOM tree, it is no longer part of:

 $para = $doc->createElement("p"); $para->setAttribute('attr', 'value'); $para->appendChild($person); <?xml version="1.0"?> <contacts> <person>Adam</person> <person>John</person> <person>Thomas</person> </contacts> 

Eve is already gone. Its parentNode is already a paragraph.

So, instead, you first want to replace, and then add a child:

 $para = $doc->createElement("p"); $para->setAttribute('attr', 'value'); $person = $person->parentNode->replaceChild($para, $person); $para->appendChild($person); <?xml version="1.0"?> <contacts> <person>Adam</person> <p attr="value"><person>Eva</person></p> <person>John</person> <person>Thomas</person> </contacts> 

Now everything is all right.

+36
source

All Articles