I have a DomElement
which unfortunately does not have the saveXML()
method that DomDocument
has.
I am trying to get the raw XML string representation of the of the DomElement.
How can I do it?
The DomElement
has a property of its DomDocument
, i.e. ownerDocument
.
Hence you can fetch the XML of the DomElement
via:
$domElementXml = $domElement->ownerDocument->saveXML($domElement);
You have to pass the node again as the ownerDocument
refers to the whole document. So running $domElement->ownerDocument->saveXML()
would fetch the entire XML of the document which could contain different DomElement
objects as well.
This expands on k0pernikus answer and includes a SimpleXMLElement variation. It works for any random DOM element without dumping the document XML:
<?php
$outerXmlAsString = $yourDomElementGoesHere
->ownerDocument
->saveXML($yourDomElementGoesHere);
// or
$outerXmlAsString = simplexml_import_dom($yourDomElementGoesHere)
->asXML();
Example:
<?php
$doc = new DOMDocument('1.0','utf-8');
$root = new DOMElement('root');
$doc->appendChild($root);
$child = new DOMElement('child');
$root->appendChild($child);
$leaf = new DOMElement('leaf','text');
$child->appendChild($leaf);
echo $child->ownerDocument->saveXML($child), PHP_EOL;
echo simplexml_import_dom($child)->asXML(), PHP_EOL;
Example output:
<child><leaf>text</leaf></child>
<child><leaf>text</leaf></child>
Test it out on 3v4l.org.
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