Remove multiple empty nodes with SimpleXML

假装没事ソ 提交于 2019-12-11 22:12:36

问题


I want to delete all the empty nodes in my XML document using SimpleXML

Here is my code :

$xs = file_get_contents('liens.xml')or die("Fichier XML non chargé");
$doc_xml = new SimpleXMLElement($xs);
foreach($doc_xml->xpath('//*[not(text())]') as $torm)
    unset($torm);   
$doc_xml->asXML("liens.xml");

I saw with a print_r() that XPath is grabbing something, but nothing is removed from my XML file.


回答1:


I know this post is a bit old but in your foreach, $torm is replaced in every iteration. This means your unset($torm) is doing nothing to the original $doc_xml object.

Instead you will need to remove the element itself:

foreach($doc_xml->xpath('//*[not(text())]') as $torm)
    unset($torm[0]);
               ###

by using a simplxmlelement-self-reference.




回答2:


$file  = 'liens.xml';
$xpath = '//*[not(text())]';

if (!$xml = simplexml_load_file($file)) {
    throw new Exception("Fichier XML non chargé");
}

foreach ($xml->xpath($xpath) as $remove) {
    unset($remove[0]);
}

$xml->asXML($file);


来源:https://stackoverflow.com/questions/5559551/remove-multiple-empty-nodes-with-simplexml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!