我使用 PHP DOM 函数从我的数据库中生成了一个 XML 文件。然后我使用 dom->save("feed.xml") 将其保存到文件中。
我面临的问题是数据库中的某些行具有空字段,从而导致这种类型的输出 -
<summary/>
因为合计字段为空。
是否可以在不影响其他节点的情况下删除这些标签?我想删除它们的原因,因为 XML 最终会被馈送到应用程序,我不希望它接受空白字段,因为这有些不一致。
有谁知道实现我想要的方法吗?
谢谢。
您可以使用
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