开发者

Remove multiple empty nodes with SimpleXML

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 char开发者_开发百科gé");
$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.


$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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜