Domanda

Come posso eliminare elementi specifici su XML usando PHP

my.xml

    <usr>
        <uid trk= "1234">
            <deleteThis>
                <mychild>here</mychild>
                <anotherchild>here</anotherchild>
            </deleteThis>
        </uid>
    </usr>

Voglio rimuovere l'elemento "Elimina" e i suoi figli

risultato:

     <usr>
        <uid trk= "1234">
        </uid>
    </usr>

Ecco il mio codice non lavorativo

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

Sembra che non abbia trovato il nodo.

È stato utile?

Soluzione

  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);
    }
  }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top