note 48814 modified in ref.simplexml by danbrown

From: Date: Mon, 18 May 2009 01:28:30 +0000
Subject: note 48814 modified in ref.simplexml by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155541@lists.php.net to get a copy of this message
A simple way to merge two SimpleXML objects. <?php /** * Pumps all child elements of second SimpleXML object into first one. * * @param object $xml1 SimpleXML object * @param object $xml2 SimpleXML object * @return void */ function simplexml_merge (SimpleXMLElement &$xml1, SimpleXMLElement $xml2) { // convert SimpleXML objects into DOM ones $dom1 = new DomDocument(); $dom2 = new DomDocument(); $dom1->loadXML($xml1->asXML()); $dom2->loadXML($xml2->asXML()); // pull all child elements of second XML $xpath = new domXPath($dom2); $xpathQuery = $xpath->query('/*/*'); for ($i = 0; $i < $xpathQuery->length; $i++) { // and pump them into first one $dom1->documentElement->appendChild( $dom1->importNode($xpathQuery->item($i), true)); } $xml1 = simplexml_import_dom($dom1); } $xml1 = simplexml_load_string('<root><child>child 1</child></root>'); $xml2 = simplexml_load_string('<root><child>child 2</child></root>'); simplexml_merge($xml1, $xml2); echo($xml1->asXml()); ?> Will output: <?xml version="1.0"?> <root> <child>child 1</child> <child>child 2</child> </root> --was-- A simple way to merge two SimpleXML objects. <?php /** * Pumps all child elements of second SimpleXML object into first one. * * @param object $xml1 SimpleXML object * @param object $xml2 SimpleXML object * @return void */ function simplexml_merge (SimpleXMLElement &$xml1, SimpleXMLElement $xml2) { // convert SimpleXML objects into DOM ones $dom1 = new DomDocument(); $dom2 = new DomDocument(); $dom1->loadXML($xml1->asXML()); $dom2->loadXML($xml2->asXML()); // pull all child elements of second XML $xpath = new domXPath($dom2); $xpathQuery = $xpath->query('/*/*'); for ($i = 0; $i < $xpathQuery->length; $i++) { // and pump them into first one $dom1->documentElement->appendChild( $dom1->importNode($xpathQuery->item($i), true)); } $xml1 = simplexml_import_dom($dom1); } $xml1 = simplexml_load_string('<root><child>child 1</child></root>'); $xml2 = simplexml_load_string('<root><child>child 2</child></root>'); simplexml_merge($xml1, $xml2); echo($xml1->asXml()); ?> Will output: <?xml version="1.0"?> <root> <child>child 1</child> <child>child 2</child> </root> http://php.net/manual/en/ref.simplexml.php

« previous php.notes (#155541) next »