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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With