0

Currently I am using unset() for removing a parent node in simpleXML, and writing it back to the XML file

I tried this code and it was working a while ago, after cleaning my code I can't find why it doesn't work all of the sudden,

The debugging approaches I took: the file can be accessed, I can enter the loop and if statement, the file gets saved (notepad++ asks me to reload), but the <systemInfo></systemInfo> does not get deleted

Here is my sample Code:

        $userorig = $_POST['user'];
        $userinfos = simplexml_load_file('userInfo.xml'); // Opens the user XML file

        foreach ($userinfos->userinfo->account as $account) 
        {       
            // Checks if the user in this iteration of the loop is the same as $userorig (the user i want to find)
            if($account->user == $userorig)
            {
                echo "hello";
                $rootSystem = $account->systemInfo;
                unset($rootSystem);
            }
        }
        $userinfos->saveXML('userInfo.xml');

My XML File:

<userinfos>
  <userinfo>
   <account>
     <user>TIGERBOY-PC</user>
     <toDump>2014-03-15 03:20:44</toDump>
     <toDumpDone>0</toDumpDone>
     <initialCheck>0</initialCheck>
     <lastChecked>2014-03-16 07:12:17</lastChecked>
     <alert>1</alert>
     <systemInfo>
          ... (many nodes and sub nodes here) ...
     </systemInfo>
   </account>
  </userinfo>
</userinfos>
Fukkatsu
  • 149
  • 1
  • 12

2 Answers2

1

Rather than iterating over the whole xml, use xpath to select the node:

$userorig = $_POST['user'];
$userinfos = simplexml_load_file('userInfo.xml'); // Opens the user XML file

$deletethisuser = $userinfos->xpath("/userinfos/userinfo/account[user = '$userorig']/systemInfo")[0];
unset($deletethisuser[0]);

Comments:

the [0] in the xpath... line requires PHP >= 5.4, in case you are running on a lower version, either update or go:

$deletethisuser = $userinfos->xpath("/userinfos/userinfo/account[user = '$userorig']/systemInfo");
unset($deletethisuser[0][0]);

Advised reading: hakre's answer in this thread: Remove a child with a specific attribute, in SimpleXML for PHP

Community
  • 1
  • 1
michi
  • 6,565
  • 4
  • 33
  • 56
  • I really actually need to iterate to the whole XML to find the user, I edit values too and run them, this code is a very short version of a 500 line one =)) ,so the foreach loop helps me get cleaner code, by the way, thanks for this tip, I never knew about xpath, I just cluelessly use XML (since it's easier to parse with the functions out there) – Fukkatsu Mar 16 '14 at 19:52
  • @SaggerAl-Saadi you can of course select a node with `xpath`and change it, no iteration required. – michi Mar 16 '14 at 21:54
-1

It worked again, sorry, I did not know why it worked, I keep running it on multiple instances, and now it works, the program has weird behavior, but tried it for around 15 tries, it did its job

Fukkatsu
  • 149
  • 1
  • 12