0

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

1
Contributor
1
Reply
2
Views
8 Years
Discussion Span
Last Post by Mapper99
0

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>

Edited by peter_budo: Keep In The Site - No Fake signatures. Create a sitewide signature within the user control panel.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.