簡體   English   中英

使用SimpleXML刪除多個空節點

[英]Remove multiple empty nodes with SimpleXML

我想使用SimpleXML刪除XML文檔中的所有空節點

這是我的代碼:

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

我通過print_r()看到XPath正在抓取某些東西,但是沒有從我的XML文件中刪除任何內容。

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

我知道這篇文章有點老,但是在您的foreach$torm在每次迭代中都會被替換。 這意味着您的unset($torm)對原始$doc_xml對象沒有任何$doc_xml

相反,您將需要刪除元素本身:

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

通過使用simplxmlelement-self-reference

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM