note 87025 deleted from function.simplexml-element-addChild by danbrown

From: Date: Sat, 15 Nov 2008 06:06:57 +0000
Subject: note 87025 deleted from function.simplexml-element-addChild by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-146578@lists.php.net to get a copy of this message
Note Submitter: Alex Dolski ---- Adding multiple children with the same name is not quite intuitive. If the goal is to create an XML string like this, with multiple fruits: <fruitbasket> <fruit> <name>orange</name> </fruit> <fruit> <name>apple</name> </fruit> <fruit> <name>grape</name> </fruit> </fruitbasket> I was trying to do something like: $sxml = new SimpleXMLElement('<fruitbasket></fruitbasket>'); $fruits = array('orange', 'apple', 'grape'); foreach ($fruits as $f) { $sxml->addChild('fruit'); $sxml->fruit->addChild('name', $f); } Won't work - the loop will keep overwriting the fruit child and you will end up with only a grape. What you have to do instead is: foreach ($fruits as $f) { $tmp = $sxml->addChild('fruit'); $tmp->addChild('name', $f); }

« previous php.notes (#146578) next »