Note that there are some explanatory texts on larger screens.

plurals
  1. POInserting a new line using DOM
    text
    copied!<p>I'm attempting to insert a new node into an XML document. I'm using simpleXML for most of the parsing but for this piece I need to use DOM. This is the function i'm using to make the addition</p> <pre><code>function simplexml_insert_after(SimpleXMLElement $sxe, SimpleXMLElement $insert, SimpleXMLElement $target) { $target_dom = dom_import_simplexml($target); $target_dom-&gt;formatOutput = true; $target_dom-&gt;preserveWhiteSpace = false; $insert_dom = $target_dom-&gt;ownerDocument-&gt;importNode(dom_import_simplexml($insert), true); if ($target_dom-&gt;nextSibling) { return $target_dom-&gt;parentNode-&gt;insertBefore($insert_dom, $target_dom-&gt;nextSibling); } else { return $target_dom-&gt;parentNode-&gt;appendChild($insert_dom); } } </code></pre> <p>And calling it like this:</p> <pre><code>$meta2 = new SimpleXMLElement("&lt;meta/&gt;"); $meta2-&gt;addAttribute('name', 'subject'); $meta2-&gt;addAttribute('value', $doc_id); $target = current($my_xml-&gt;xpath('//meta[last()]')); simplexml_insert_after($my_xml, $meta2, $target); </code></pre> <p>My Problem is that its inserting the new node immediately after the target rather than on a new line so the resulting XML looks like this:</p> <pre><code>&lt;meta content="a" name="ap-category"/&gt; &lt;meta content="bx" name="ap-format"/&gt;&lt;meta name="subject" value="urn:blah"/&gt; </code></pre> <p>When I'd like it to look like this:</p> <pre><code>&lt;meta content="a" name="ap-category"/&gt; &lt;meta content="bx" name="ap-format"/&gt; &lt;meta name="subject" value="urn:blah"/&gt; </code></pre> <p>I've tried changing preserveWhiteSpace to true, but it did not help. How do i go about adding a new line before inserting that node?</p> <p><strong>edit</strong> Here is the fix that worked:</p> <pre><code> function simplexml_insert_after(SimpleXMLElement $sxe, SimpleXMLElement $insert,SimpleXMLElement $target) { $target_dom = dom_import_simplexml($target); $target_dom-&gt;formatOutput = true; $target_dom-&gt;preserveWhiteSpace = false; $insert_dom = $target_dom-&gt;ownerDocument-&gt;importNode(dom_import_simplexml($insert), true); if ($target_dom-&gt;nextSibling) { $result = $target_dom-&gt;parentNode-&gt;insertBefore($insert_dom, $target_dom-&gt;nextSibling); $target_dom-&gt;parentNode-&gt;insertBefore($target_dom-&gt;ownerDocument-&gt;createTextNode("\n"), $result); return $result } else { return $target_dom-&gt;parentNode-&gt;appendChild($insert_dom); } } </code></pre>
 

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