Forum Moderators: coopster

Message Too Old, No Replies

PHP - SimpleXML remove node

         

username

6:59 am on Apr 1, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



Hi, I have a basic XML structure, that I am trying to remove a node from if the node value is equal to the integer I am looking for. i.e Delete node if value is 48.

My structure i:

<values>
<user>
<userid>21</userid>
</user>
<user>
<userid>48</userid>
</user>
</values>

I have read quite a bit on this, and I believe this cannot be done with SimpleXML, and needs to be DOM. I am looking for a simple solution to this. Does anyone know how to delete the entire <user> tag if the <userid> of that tag is 48?

Thanks in advance. Hope I am clear enough.

username

10:04 pm on Apr 1, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



So does anyone have any ideas on this one?

Thanks :)

eeek

10:03 pm on Apr 3, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



So does anyone have any ideas on this one?

It's not clear what you are asking for or why you brought DOM into this.

coopster

9:27 pm on Apr 4, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Actually, it is a common question asked by PHP SimpleXML users. In short, there is no "nice" way to remove nodes with simpleXML. For example, using your code above:
$string = <<<ENDOFHTML 
<values>
<user>
<userid>21</userid>
</user>
<user>
<userid>48</userid>
</user>
</values>
ENDOFHTML;
$xml = simplexml_load_string($string);
$count = 0;
foreach ($xml as $user) {
if ($user->userid == 21) {
unset($xml->user[$count]); break;
}
$count++;
}
echo $xml->asXML();
exit;

Note how the counter must be used and then a break is used after removing the node? The only other way around the break here is to count the number of array nodes and loop over it in reverse because the array gets reindexed. It's ugly. So yes, it can be done but you are much better off using the DOM methods.

username

10:47 pm on Apr 8, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



Thanks Coopster. Your suggestion was really helpful. I made some modifications, and this is a reasonably tight, but most importantly working solution:

$xmlfile = ".. .xml"; (location of xml file)
$xmlstr = file_get_contents("$xmlfile");
$xml = new SimpleXMLElement($xmlstr);

$count = 0;
foreach ($xml as $user){
if ($user->userid == "02345678"){
unset($xml->user[$count]); break;
}
$count++;
}
echo $xml->asXML();

$handle = fopen("$xmlfile", "w");
fwrite($handle, $xml->asXML());
fclose($handle);

exit;
?>