Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, how can I get the Outer XML from a DOMNode?

Tags:

php

xml

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".

like image 846
Michael Pryor Avatar asked Jun 11 '09 20:06

Michael Pryor


2 Answers

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.

like image 198
rojoca Avatar answered Sep 25 '22 20:09

rojoca


After an hour spent, I came up with this (it seems the best solution)

$node->ownerDocument->saveXml($node);
like image 24
Ludovico Grossi Avatar answered Sep 21 '22 20:09

Ludovico Grossi