Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get string for a DomElement?

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?

like image 952
k0pernikus Avatar asked Dec 15 '15 18:12

k0pernikus


2 Answers

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.

like image 50
k0pernikus Avatar answered Sep 26 '22 09:09

k0pernikus


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.

like image 42
TylerY86 Avatar answered Sep 25 '22 09:09

TylerY86