Hi there,

I am trying to delete XML nodes using PHP. Here is a sample of my xml file.

<users>
     <user>
     <fullname>PC1</fullname>
     <flooor>4</floor
     </user>
     <user>
     <fullname>PC2</fullname>
     <flooor>3</floor
     </user>
</users>

Here is my code so far:

<?php

$users = new DOMDocument();
$users->load("officedata.xml");
$suser = simplexml_load_file("officedata.xml");
$count = 0;

foreach($suser->user as $user) {

     if ($user['fullname'] == "PC1") {
    $users->documentElement->removeChild($users-       documentElement->childNodes->item($count));
    $count--;
    }
    $count++
}
$users->save("officedata.xml");

?>

Any idea why this won't work? If I remove the IF statement, all of the XML data gets removed.

Thanks in advance,

Mapper

For those of you could not figure this one out, after a few tries I got it:

$users = new DOMDocument();
$users->load("officedata.xml");

$suser = simplexml_load_file("officedata.xml");
$count = 0;

$user = $users->getElementsByTagName("user");

foreach($user as $value)
{
   $count++;
   $tasks = $value->getElementsByTagName("fullname");
   $task  = $tasks->item(0)->nodeValue;

   if ($task == "PC1") {
    $users->documentElement->removeChild($users->documentElement->childNodes->item($count));
   }
}

$users->save("officedata.xml");
?>

Works like a charm and is a very useful code snippet for deleting XML records using PHP!

Mapper
<FAKE SIGNATURE>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.