note 68618 modified in function.simplexml-element-addChild by danbrown

From: Date: Wed, 16 Sep 2009 16:39:44 +0000
Subject: note 68618 modified in function.simplexml-element-addChild by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-160747@lists.php.net to get a copy of this message
Method to append (Simple)XMLElements to each other. <?php class XMLElement extends SimpleXMLElement { public function addElement (XMLElement $xmlTree,$root=false) { if ($root) { $child = $this->addChild ($xmlTree->getName()); foreach ($xmlTree->attributes() as $k => $v) { $child->addAttribute($k,$v); } $child->addElement($xmlTree); } else { foreach ($xmlTree as $childName => $childTree) { $child = $this->addChild($childName,(string) $childTree); // this is not comletely correct foreach ($childTree->attributes() as $k => $v) { $child->addAttribute($k,$v); } $child->addElement($childTree->children()); } } } } $xmlMovies = "<movies><movie name=\"Shawshank Redemption\"><plot>The life of Andy Dufresne changes when he is convicted and jailed for the murder of his wife.</plot></movie></movies>"; $elMovies = new XMLElement($xmlMovies); $xmlGodfather = "<movie name=\"Godfather\"><plot>The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.</plot></movie>"; $elGodfather = new XMLElement ($xmlGodfather); $elMovies->addElement($elGodfather,true); echo $elMovies->asXML(); ?> --was-- <?php class XMLElement extends SimpleXMLElement { public function addElement (XMLElement $xmlTree,$root=false) { if ($root) { $child = $this->addChild ($xmlTree->getName()); foreach ($xmlTree->attributes() as $k => $v) { $child->addAttribute($k,$v); } $child->addElement($xmlTree); } else { foreach ($xmlTree as $childName => $childTree) { $child = $this->addChild($childName,(string) $childTree); // this is not comletely correct foreach ($childTree->attributes() as $k => $v) { $child->addAttribute($k,$v); } $child->addElement($childTree->children()); } } } } $xmlMovies = "<movies><movie name=\"Shawshank Redemption\"><plot>The life of Andy Dufresne changes when he is convicted and jailed for the murder of his wife.</plot></movie></movies>"; $elMovies = new XMLElement($xmlMovies); $xmlGodfather = "<movie name=\"Godfather\"><plot>The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.</plot></movie>"; $elGodfather = new XMLElement ($xmlGodfather); $elMovies->addElement($elGodfather,true); echo $elMovies->asXML(); ?> Method to append (Simple)XMLElements to each other. http://php.net/manual/en/function.simplexml-element-addChild.php

« previous php.notes (#160747) next »