问题
如何在PHP中删除空的xml标记?
示例:
$value1 = "2";
$value2 = "4";
$value3 = "";
xml = '<parentnode>
<tag1> ' .$value1. '</tag1>
<tag2> ' .$value2. '</tag2>
<tag3> ' .$value3. '</tag3>
</parentnode>';XML结果:
<parentnode>
<tag1>2</tag1>
<tag2>4</tag2>
<tag3></tag3> // <- Empty tag
</parentnode>我想要的!
<parentnode>
<tag1>2</tag1>
<tag2>4</tag2>
</parentnode>不带"tag3“等空标记的XML
谢谢!
发布于 2013-09-12 02:07:33
通过使用Xpath,我的生产PHP目标代码的解决方案是:
/*
* Remove empty (no children) and blank (no text) XML element nodes, but not an empty root element (/child::*).
* This does not work recursively; meaning after empty child elements are removed, parents are not reexamined.
*/
foreach( $this->xml->xpath('/child::*//*[not(*) and not(text()[normalize-space()])]') as $emptyElement ) {
unset( $emptyElement[0] );
}注意,不需要使用PHP DOM、DOMDocument、DOMXPath或dom_import_simplexml()。
//this is a recursively option
do {
$removed = false;
foreach( $this->xml->xpath('/child::*//*[not(*) and not(text()[normalize-space()])]') as $emptyElement ) {
unset( $emptyElement[0] );
$removed = true;
}
} while ($removed) ;https://stackoverflow.com/questions/8603237
复制相似问题