Question

Is it possible to get xml string form DomDocument or SimpleXml without root node? DomDocument->saveXml() returns this:

<root>
    <item>text</item>
    <item>text</item>
</root>

And I need:

<item>text</item>
<item>text</item>

Can I get this with DomDocument? Is there any way to do this without regexp?

Was it helpful?

Solution

The "inner XML" is like "inner HTML" of the innerHTML property, so used in Javascript and other languages... I think we can ignore @michi comentary requiring some explanation. About @CBroe commentary: not make sense if you imagine DOMDocumentFragment, or a string-XML replace from a innerXML to another (ex. filtered) XML. Your good example (of item list) is a string-XML that can be also converted to a DOMNodeList.


The fasted and simplest way to get all XML is using the saveXML(), and it return a string that contains the string that you whant.

There are two ways to cut-off the part (a kind of "trim tag") that you not need:

By DOM

A loop over all $node->childNodes, concatenating each subnode by saveXML($subnode).

By regex

Perhaps more simple and fast, but not secure, something like

$innerXML = preg_replace(
    '#^\s*<([a-z0-9_:]+)[^>]*>(.+?)</\\1>\s*$#s', 
    '$2', 
    $dom->saveXML($node)
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top