0

I'm experimenting with SimpleXML for PHP and I was wondering about something. The XML document is like this:

<?xml version="1.0" standalone="yes"?>
<users>
    <user id="1">
        <name>Jan</name>
        <sex>Male</sex>
        <password>fu9f8w9080fd9id9di093r9f9if9if9d0sfu</password>
        <avatar type="remote">http://www.avatars.com/av_1.gif</avatar>
    </user>

    <user id="3">
        <name>Piet</name>
        <sex>Male</sex>
        <password>fu9f8w9080fd9id9di093r9f9if9676674bv</password>
        <avatar type="local">html/avatars/Eten%20en%20drinken/cola.png</avatar>
    </user>

    <user id="4">
        <name>Ilse</name>
        <sex>Female</sex>
        <password>fu9f8w9080fd9id9di4564564564539d0sfu</password>
        <avatar type="none"/>
    </user>

    <user id="5">
        <name>Els</name>
        <sex>Female</sex>
        <password>fu9f8w9080fd9id9di09gi5uy378wrfuih4w</password>
        <avatar type="upload">avatar_1.gif</avatar>
    </user>
</users>

I made a descending for loop to remove all female users, but I was wondering if there were other methods, using foreach to iterate through the users or using xpath to select all records of females and remove them all at once.

Also, I was wondering if you could remove all nodes without iterating through all users.

So far I have figured out that "removeChild" does not work in simpleXML, or have I missed something.

Thanks,

Coenj

Coenj
  • 27
  • 1
  • 7

1 Answers1

0

In fact, there's no removeChild in PHP: http://www.php.net/manual/en/book.simplexml.php

You can select with xpathand then use a loop and unset:

$xml = simplexml_load_string($x); // assume XML in $x
$females = $xml->xpath("/users/user[sex = 'Female']");
foreach ($females as $female) unset($female[0]);

See it working: https://eval.in/108813

michi
  • 6,565
  • 4
  • 33
  • 56