Supprimer les données Xml en utilisant php
-
27-10-2019 - |
Question
Comment supprimer des éléments spécifiques sur XML en utilisant php
my.xml
<usr>
<uid trk= "1234">
<deleteThis>
<mychild>here</mychild>
<anotherchild>here</anotherchild>
</deleteThis>
</uid>
</usr>
Je veux supprimer l'élément « de deleteThis » et ses enfants
résultat:
<usr>
<uid trk= "1234">
</uid>
</usr>
voici mon code non-travail
index.php
$xml = new DOMDocument;
$xml->load('my.xml');
$thedocument = $xml->documentElement;
$list = $thedocument->getElementsByTagName('uid');
foreach ($list as $domElement){
$attrValue = $domElement->getAttribute('trk');
if ($attrValue == "1234") { //if <uid trk= "1234">
$valY = $domElement->getElementsByTagName('deleteThis');
$thedocument->removeChild($valY);
}
}
$xml->save("my.xml");
Il semble qu'il n'a pas trouvé le nœud.
La solution
if ($attrValue == "1234") { //if <uid trk= "1234">
$valY = $domElement->getElementsByTagName('deleteThis');
//$valY is a DOMNodeList, that you happen to know there is only one doesnt matter
foreach($valY as $delnode){
$delnode->parentNode->removeChild( $delnode);
}
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow