Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to remove empty nodes from XML in PHP
    primarykey
    data
    text
    <p>I am submitting a form (after some validation) and compiling some xml like so:</p> <pre><code>$sxe = new SimpleXMLElement($xmlstr); $MyFirstNode = $sxe-&gt;addChild('MyFirstNode', $_POST["MyTitle"]); $MySecondNode = $sxe-&gt;addChild('MySecondNode'); $MyTHIRDNode = $MySecondNode-&gt;addChild('MyTHIRDNode', $_POST["FormElementName"]); </code></pre> <p>After this, I am writing the xml to a document using the following code;</p> <pre><code>$myFile = "myfilename.xml"; $fh = fopen($myFile, 'w') or die("can't open file"); fwrite($fh, $sxe-&gt;asXML()); fclose($fh); </code></pre> <p>In one scenario I need to produce the XML including any empty nodes. So in the above example, if <code>FormElementName</code> was empty it would be fine (producing something like <code>&lt;MyTHIRDNode&gt;&lt;/MyTHIRDNode&gt;</code></p> <p>However, in another scenario I need to remove all these empty nodes, so I am left with the ones that contain some sort of data:</p> <pre><code>&lt;node&gt; &lt;one&gt;Hello&lt;/one&gt; &lt;two&gt;&lt;/two&gt; // &lt;- Empty &lt;three&gt;World!&lt;/three&gt; &lt;/node&gt; // Becomes... &lt;node&gt; &lt;one&gt;Hello&lt;/one&gt; &lt;three&gt;World!&lt;/three&gt; &lt;/node&gt; </code></pre> <p>I have an if statement ready to differentiate between the two scenarios:</p> <pre><code>if ($_POST["operation"] == "UPDATE") { //do something } </code></pre> <p>However, I am not sure how to iterate through my '$sxe' and remove these empty nodes.</p> <p>Any help is much appreciated :)</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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