Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/251.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从PHP生成的XML文件中剥离空白XML标记?_Php_Xml - Fatal编程技术网

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

从PHP生成的XML文件中剥离空白XML标记?,php,xml,Php,Xml,我使用PHPDOM函数从数据库生成了一个XML文件。然后我使用dom->save(“feed.xml”)将其保存到一个文件中 我面临的问题是,我的数据库中的某些行具有空feld,导致这种类型的输出- <summary/> 因为摘要字段为空 是否可以在不影响其他节点的情况下删除这些标记?我之所以要删除它们,是因为XML最终将被提供给应用程序,我不希望它包含在空白字段中,因为这有点不一致 有人知道如何实现我的愿望吗 谢谢。您可以使用xpath()选择所有空节点并删除它们: 示例X

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

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

<summary/> 

因为摘要字段为空

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

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

谢谢。

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

示例XML:

<root>
    <test/>
    <test></test>
    <test>
        <name>Michi</name>
        <name/>
    </test>    
</root>
$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>
输出:

<root>
    <test/>
    <test></test>
    <test>
        <name>Michi</name>
        <name/>
    </test>    
</root>
$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>

米奇

查看它是否工作:

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