Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You're on the right track. The CDATA sections are text for outer document, the xml fragment inside a CDATA is its own document or fragment. </p> <pre><code>$xml = new DOMDocument("1.0","UTF-8"); $xml-&gt;appendChild($historyNode = $xml-&gt;createElement('history')); $innerXml = new DOMDocument("1.0","UTF-8"); $innerXml-&gt;appendChild($nameNode = $innerXml-&gt;createElement('name')); $nameNode-&gt;appendChild($ageNode = $innerXml-&gt;createElement('age')); $fragment = $innerXml-&gt;saveXml($innerXml-&gt;documentElement); $historyNode-&gt;appendChild($xml-&gt;createCDATASection($fragment)); $xml-&gt;formatOutput = true; echo $xml-&gt;saveXML(); </code></pre> <p>Output:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;history&gt;&lt;![CDATA[&lt;name&gt;&lt;age/&gt;&lt;/name&gt;]]&gt;&lt;/history&gt; </code></pre> <p>This will only work if the fragment has a single root node (is a valid xml document). If it has several nodes on the top level you will need a dummy node. I added 'address' to the next example to show the difference:</p> <pre><code>$xml = new DOMDocument("1.0","UTF-8"); $xml-&gt;appendChild($historyNode = $xml-&gt;createElement('history')); $innerXml = new DOMDocument("1.0","UTF-8"); $innerXml-&gt;appendChild($fragmentNode = $innerXml-&gt;createElement('fragment')); $fragmentNode-&gt;appendChild($nameNode = $innerXml-&gt;createElement('name')); $nameNode-&gt;appendChild($ageNode = $innerXml-&gt;createElement('age')); $fragmentNode-&gt;appendChild($addressNode = $innerXml-&gt;createElement('address')); $fragment = ''; foreach ($fragmentNode-&gt;childNodes as $childNode) { $fragment .= $innerXml-&gt;saveXml($childNode); } $historyNode-&gt;appendChild($xml-&gt;createCDATASection($fragment)); $xml-&gt;formatOutput = true; echo $xml-&gt;saveXML(); </code></pre> <p>Output:</p> <pre><code>&lt;history&gt;&lt;![CDATA[&lt;name&gt;&lt;age/&gt;&lt;/name&gt;&lt;address/&gt;]]&gt;&lt;/history&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload