1

我正在提交一个表单(经过一些验证)并像这样编译一些 xml:

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

在此之后,我使用以下代码将 xml 写入文档;

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

在一种情况下,我需要生成包含任何空节点的 XML。所以在上面的例子中,如果FormElementName是空的就可以了(产生类似的东西<MyTHIRDNode></MyTHIRDNode>

但是,在另一种情况下,我需要删除所有这些空节点,所以我只剩下包含某种数据的节点:

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

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

我准备了一个 if 语句来区分这两种情况:

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

但是,我不确定如何遍历我的 '$sxe' 并删除这些空节点。

任何帮助深表感谢 :)

4

1 回答 1

1

如果(感觉很懒)这样做:

$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

代码是在这里编写的,没有经过测试。应该管用!

于 2012-10-24T13:20:09.703 回答