Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simplexml_import_dom(): Invalid Nodetype to import - which DOMNode sub-types are supported?

Tags:

php

xml

simplexml

From time to time, the simplexml_import_dom() function gives me the following error when the passed DOMNode is not of a compatible sub-type:

simplexml_import_dom(): Invalid Nodetype to import

So I'm wondering which DOMNode types are valid to import?

like image 785
hakre Avatar asked Dec 14 '25 01:12

hakre


1 Answers

First of all, the DOMNode you import via simplexml_import_dom must be associated to a document. That is independent of it's DOMNode sub-type, a node without a document will be rejected:

simplexml_import_dom(): Imported Node must have associated Document

Next to that, the imported node must be of type DOMElement.

And those two are the only requirements (see source).

Summary: You can import any DOMElement which has a ownerDocument into simplexml.

If you need to import a DOMNode that has no document, create one and import it.

/** @var XMLReader $reader */
$node = $reader->expand();

if (!$node instanceof DOMElement) {
    throw new UnexpectedValueException(
        sprintf('Expected DOMElement, %s given.', get_class($node))
    );
}

$doc  = new DomDocument();
$node = $doc->importNode($node, true);

$sxnl = simplexml_import_dom($node);

If the node is not a DOMElement then it is more tricky to work-around and depends on what you need in concrete, there is no simple fall-back, as much as there is no simple in simplexml at that point.

To find out which nodetype a SimpleXMLElement represents, please see:

  • How to tell apart SimpleXML objects representing element and attribute?
like image 114
hakre Avatar answered Dec 15 '25 16:12

hakre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!