[英]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.