简体   繁体   中英

How to remove empty nodes from XML in PHP

I am submitting a form (after some validation) and compiling some xml like so:

$sxe = new SimpleXMLElement($xmlstr);
$MyFirstNode = $sxe->addChild('MyFirstNode', $_POST["MyTitle"]); 
$MySecondNode = $sxe->addChild('MySecondNode');
$MyTHIRDNode = $MySecondNode->addChild('MyTHIRDNode', $_POST["FormElementName"]);

After this, I am writing the xml to a document using the following code;

$myFile = "myfilename.xml";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $sxe->asXML());
fclose($fh);

In one scenario I need to produce the XML including any empty nodes. So in the above example, if FormElementName was empty it would be fine (producing something like <MyTHIRDNode></MyTHIRDNode>

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:

<node>
    <one>Hello</one>
    <two></two> // <- Empty
    <three>World!</three>
</node>

// Becomes...
<node>
    <one>Hello</one>
    <three>World!</three> 
</node>

I have an if statement ready to differentiate between the two scenarios:

if ($_POST["operation"] == "UPDATE") {
    //do something
}

However, I am not sure how to iterate through my '$sxe' and remove these empty nodes.

Any help is much appreciated :)

if(feeling lazy) do this:

$xmlsz = $xml->asXML(); // Get XML code from your SXE
// Keep retrying as some empty nodes may contain other empty nodes
while(true){
    $xmlsz_ref = $xmlsz; // keep old version as reference
    // Remove <node></node> empty nodes
    $xmlsz = preg_replace('~<[^\\s>]+>\\s*</\\1>~si', null, $xmlsz);
    // Remove <node /> empty nodes
    $xmlsz = preg_replace('~<[^\\s>]+\\s*/>~si', null, $xmlsz);
    if($xmlsz_ref === $xmlsz) break; // If not changed, break!
}
$xmlsz = simplexml_load_string($xmlsz); // reparse XML code to your SEX

Code was written here and not tested. Should work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM