从PHP生成的XML文件中剥离空白XML标记?

时间:2014-12-16 12:15:32

标签: php xml

我使用PHP DOM函数从我的数据库生成了一个XML文件。然后我使用dom-> save(“feed.xml”)将其保存到文件中。

我面临的问题是我的数据库中的某些行有空字段,导致这种类型的输出 -

<summary/> 

,因为摘要字段为空。

是否可以在不影响其他节点的情况下删除这些标签?我想删除它们作为XML的原因最终将被提供给一个应用程序,我不希望它采用空白字段,因为这有点不一致。

有没有人知道如何实现我的愿望?

感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用xpath()选择所有空节点并删除它们:

示例XML:

<root>
    <test/>
    <test></test>
    <test>
        <name>Michi</name>
        <name/>
    </test>    
</root>

<强> PHP:

$xml = simplexml_load_string($x); // assume XML in $x

// select any node at any position in the tree that has no children and no text
// store them in array $results
$results = $xml->xpath("//*[not(node())]");

// iterate and delete
foreach ($results as $r) unset($r[0]);

// display new XML
echo $xml->asXML(); 

<强>输出:

<?xml version="1.0"?>
<root>
    <test>
        <name>Michi</name>    
    </test>    
</root>

看到它有效:https://eval.in/236071