Re: remove SimpleXML nodes

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Javier Ruiz wrote:
Hi all,

So I want to do...

$xmlDatabase = new SimpleXMLElement($myXML);
foreach ($xmlDatabase as $oneTable)
{
  if ($oneTable['name'] == 'two')
  {
     ///  ---- HERE I WANT TO DELETE THE $oneTable NODE
     unset($oneTable);   // <-- and this doesn't work...
  }
}


any ideas?


The answer is simple, everybody else seems to have missed it. foreach() makes a copy of the array before working on it. Changes made to $oneTable would obviously never affect the original. You're just unsetting a temporary variable that's going to be overwritten next time through the loop anyhow.

You should have better luck with this code:

$xmlDatabase = new SimpleXMLElement($myXML);
foreach ($xmlDatabase as $key => $oneTable)
{
  if ($oneTable['name'] == 'two')
  {
     ///  ---- HERE I WANT TO DELETE THE $oneTable NODE
     unset($xmlDatabase[$key]);
  }
}

What that is doing is having foreach also get the key of the array element that $oneTable represents. It then does the unset() on the original table instead of the copy. Remember that all array elements have keys, even if you didn't set one or it doesn't look like they should. In this case, you don't know what the key is internally, and you don't care either.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux