从现有XML中删除值

时间:2017-04-11 11:40:06

标签: php arrays xml object

考虑具有值的XMLsample并且我想删除这些值并显示或存储XML文件,只包含标记和属性(如果有的话),而不是元素中的任何值 例如:

<hello> hi how </hello>将此转换为<hello></hello>,我的XML也有2个或3个深度子元素

1 个答案:

答案 0 :(得分:0)

$xml = simplexml_load_string($string); 
ClearRecurse($xml); 
echo $xml->asXML();

function ClearRecurse(&$xml) 
{ 
   $children = $xml->children();
   if (empty($children)) {
     $xml[0] = "";                   // No child - clear value
   }
   else {
     foreach($xml->children() as $key=>$value) {
        ClearRecurse($value);        // Repeat for all descendants
      }     
   } 
} 

<强> demo on eval.in