tags:

views:

391

answers:

2

If you have DOMNode in PHP, how can you get the outer xml (i.e. the all of the XML that is inside this element plus the element itself)?

For example, lets say this is the structure

<car>
 <tire>Michelin</tire>
 <seats>Leather</seats>
 <type>
   <color>red</color>
   <make>Audi</make>
 </type>
</car>

And I have a pointer to the <type> node... I want to get back

<type>
    <color>red</color>
    <make>Audi</make>
</type>

If I just ask for the text, I get back "redAudi".

+4  A: 

You need a DOMDocument:

// If you don't have a document already:
$doc = new DOMDocument('1.0', 'UTF-8');

echo $doc->saveXML($node); // where $node is your DOMNode

Check DOMDocument::saveXML in the docs for more info.

When you pass a DOMNode to saveXML() you get back only the contents of that node not the whole document.

rojoca
No, I have a DOMNode (a subnode of the DOMDocument) and I need to extract out the InnerXML...
Michael Pryor
rojoca is saying that the DOMNode class doesn't have a method to extract the original XML. Instead you need to pass the node to a brand new DOM document to re-encode it as XML.
Josh
+1: i didn't know you could do that..!
nickf
A: 

You could try something like:

function getInnerXml(DomNode $node){
  $xml = '';
  foreach($node->childNodes as $childNode){
    $xml .= $node->ownerDocument->saveXml($childNode);
  }
  return $xml;
}
why not just `return $node->ownerDocument->saveXxml($node)` ?
nickf
but like, you know... without the typo.
nickf