Delete XML nodes failing...

Thread Solved

Join Date: Apr 2008
Posts: 30
Reputation: Mapper99 is an unknown quantity at this point 
Solved Threads: 0
Mapper99 Mapper99 is offline Offline
Light Poster

Delete XML nodes failing...

 
0
  #1
Oct 1st, 2009
Hi there,

I am trying to delete XML nodes using PHP. Here is a sample of my xml file.
  1. <users>
  2. <user>
  3. <fullname>PC1</fullname>
  4. <flooor>4</floor
  5. </user>
  6. <user>
  7. <fullname>PC2</fullname>
  8. <flooor>3</floor
  9. </user>
  10. </users>

Here is my code so far:

  1. <?php
  2.  
  3. $users = new DOMDocument();
  4. $users->load("officedata.xml");
  5. $suser = simplexml_load_file("officedata.xml");
  6. $count = 0;
  7.  
  8. foreach($suser->user as $user) {
  9.  
  10. if ($user['fullname'] == "PC1") {
  11. $users->documentElement->removeChild($users- documentElement->childNodes->item($count));
  12. $count--;
  13. }
  14. $count++
  15. }
  16. $users->save("officedata.xml");
  17.  
  18. ?>

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

Thanks in advance,

Mapper
Reply With Quote Quick reply to this message  
Join Date: Apr 2008
Posts: 30
Reputation: Mapper99 is an unknown quantity at this point 
Solved Threads: 0
Mapper99 Mapper99 is offline Offline
Light Poster

Re: Delete XML nodes failing...

 
0
  #2
Oct 2nd, 2009
For those of you could not figure this one out, after a few tries I got it:

  1. $users = new DOMDocument();
  2. $users->load("officedata.xml");
  3.  
  4. $suser = simplexml_load_file("officedata.xml");
  5. $count = 0;
  6.  
  7. $user = $users->getElementsByTagName("user");
  8.  
  9. foreach($user as $value)
  10. {
  11. $count++;
  12. $tasks = $value->getElementsByTagName("fullname");
  13. $task = $tasks->item(0)->nodeValue;
  14.  
  15. if ($task == "PC1") {
  16. $users->documentElement->removeChild($users->documentElement->childNodes->item($count));
  17. }
  18. }
  19.  
  20. $users->save("officedata.xml");
  21. ?>

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

Mapper
<FAKE SIGNATURE>
Last edited by peter_budo; Oct 2nd, 2009 at 10:34 am. Reason: Keep In The Site - No Fake signatures. Create a sitewide signature within the user control panel.
Reply With Quote Quick reply to this message  
Reply

Tags
delete, nodes, php, xml

This thread has been marked solved.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the PHP Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC