Mansa
Mansa

Reputation: 2325

XML PHP Delete specific Child if?

I have a xml document looking like this:

<?xml version="1.0" encoding="ISO-8859-1"?>
<library>
  <invites>
    <invite>
      <username>0</username>
      <userid>0</userid>
    </invite>
    <invite>
      <username>Danielle</username>
      <gameid>87808</gameid>
    </invite>
    <invite>
      <username>Petra</username>
      <userid>978</userid>
    </invite>
  </invites>
</library>

Now, I want to delete the <invite> with Danielle but I am not sure how? I am using this right now but this will only delete the first record?

$file = 'my.xml';
$fp = fopen($file, "rb") or die("cannot open file");
$str = fread($fp, filesize($file));

$xml = new DOMDocument("1.0", "ISO-8859-1");
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML($str) or die("Error");

$root   = $xml->documentElement;
$fnode  = $root->firstChild;

$ori    = $fnode->childNodes->item(0);

$fnode->removeChild($ori);

$xml->save($file);

I want to be able to delete depending on either gameid or userid. How do I go about this?

Thanks in advance :-)

Upvotes: 0

Views: 97

Answers (2)

web-nomad
web-nomad

Reputation: 6003

Try this:

Using DOM & DOMXPath.

<?php
$dom = new DOMDocument( '1.0' );
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

// load the xml file
$dom->loadXML( '<?xml version="1.0" encoding="ISO-8859-1"?>
<library>
  <invites>
    <invite>
      <username>0</username>
      <userid>0</userid>
    </invite>
    <invite>
      <username>Danielle</username>
      <gameid>87808</gameid>
    </invite>
    <invite>
      <username>Petra</username>
      <userid>978</userid>
    </invite>
  </invites>
</library>', LIBXML_NOBLANKS );
$xpath = new DOMXPath($dom);

//find all 'invite' nodes with username=Danielle and delete'em.
$node = $xpath->query("//invite[username='Danielle']");

// if found, append the new "value" node
if( $node->length ) {
    foreach ($node as $n) {
        $n->parentNode->removeChild( $n );
    }
}

header('content-type: text/xml');
echo $dom->saveXML();
?>

Hope this helps.

Upvotes: 1

Bart Friederichs
Bart Friederichs

Reputation: 33573

You could use XPath to select all nodes that have a certain userid or gameid: http://www.w3schools.com/xpath/default.asp

Upvotes: 1

Related Questions