2011-04-05 96 views
0

刪除多個空的節點我想用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文件中刪除。

+0

我不相信你實際上未設置()在$ doc_xml中的元素上。讓我查看SimpleXML以查看如何正確刪除節點。 – beta0x64 2011-04-05 23:03:51

+0

[PHP SimpleXML - 刪除xpath節點]的可能重複(http://stackoverflow.com/questions/2442314/php-simplexml-remove-xpath-node) – 2011-04-06 18:02:11

回答

1

我知道這個帖子有點舊,但是在你的foreach,$torm被替換爲每次迭代。這意味着您的unset($torm)對原始$doc_xml對象沒有任何作用。通過使用simplxmlelement自基準

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

相反,你將需要刪除的元素本身。

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); 
+0

'dom_import_simplexml()'不是必須的,你可以刪除元素在simplexml中直接使用'unset'節點而不切換到DOM([simplexml self reference](http://stackoverflow.com/a/4137027/367456))。 – hakre 2013-06-22 07:38:06