【问题标题】:Stripping blank XML tags from PHP generated XML files?从 PHP 生成的 XML 文件中去除空白 XML 标记?
【发布时间】:2014-12-16 12:15:31
【问题描述】:

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

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

<summary/> 

因为汇总字段为空。

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

有人知道实现我想要的方法吗?

谢谢。

【问题讨论】:

  • 能否在创建节点之前不检查该字段的值是否为“空”?
  • 理论上,在遍历我的查询结果之前,我可以检查哪些是空的?
  • @JesseOrange 在循环查询时检查值是否为空,如果不是,则设置节点,否则不要添加空节点。

标签: php xml


【解决方案1】:

您可以使用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

【讨论】:

    猜你喜欢
    • 2013-09-03
    • 2023-01-19
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 2011-03-19
    • 2011-10-18
    • 1970-01-01
    相关资源
    最近更新 更多