-2

How to remove all xml children with a given element name in PHP with SimpleXML?

<xml>
<computer></computer>
<book></book>
<book></book>
</xml>

I need a quick way to remove all "book" elements. Thanks!

user2799603
  • 873
  • 3
  • 13
  • 19
  • 2
    Try yourself first, please. If you're stuck somewhere, come back with that specific question. – Johannes H. Feb 24 '14 at 18:09
  • No, I would like to use simple xml actually – user2799603 Feb 24 '14 at 18:29
  • YOu cannot (I repeat: cannot) remove nodes (or rearrange the document tree) with SimpleXML. (well, you can just `unset`a node you selected, but it only works for single nodes.) It doesn'T have any remove methods. – Johannes H. Feb 24 '14 at 19:07

1 Answers1

0

select all nodes with xpath and unset them:

$xml = simplexml_load_string($x); // assume XML in $x

$books = $xml->xpath("//book");
foreach ($books as $book) unset($book[0]);

see it in action: https://eval.in/105257

michi
  • 6,565
  • 4
  • 33
  • 56