1

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.

Jeff Noel
  • 7,500
  • 4
  • 40
  • 66
Servernumber
  • 305
  • 4
  • 10
  • I do not believe that you are actually unset()'ing on the element in $doc_xml. Let me look up SimpleXML to see how to properly remove a node. – 0x1F602 Apr 05 '11 at 23:03
  • possible duplicate of [PHP SimpleXML - Remove xpath node](http://stackoverflow.com/questions/2442314/php-simplexml-remove-xpath-node) –  Apr 06 '11 at 18:02

2 Answers2

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);
hakre
  • 193,403
  • 52
  • 435
  • 836
dafi
  • 21
  • 4
  • `dom_import_simplexml()` is not necessary, you can remove the element node directly with `unset` in simplexml without switching to DOM ([simplexml self reference](http://stackoverflow.com/a/4137027/367456)). – hakre Jun 22 '13 at 07:38
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.

hakre
  • 193,403
  • 52
  • 435
  • 836
Beshoy Girgis
  • 465
  • 5
  • 11