note 78855 modified in ref.simplexml by danbrown

From: Date: Mon, 18 May 2009 01:17:25 +0000
Subject: note 78855 modified in ref.simplexml by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155509@lists.php.net to get a copy of this message
This function could be useful to somebody if you want to insert an XML into another when building an XML from many different files. Note that you must specify a name for the node in which the child files content/node will be inserted : foreach (xxx as $firstCondition){ $xml_parent = simplexml_load_file("$firstCondition.xml"); foreach (yyy as $secondCondition){ $xml_children = simplexml_load_file("secondCondition.xml"); SimpleXMLElementObj_into_xml($xml_parent , $xml_children , 'linkingNode'); //will insert every nodes of the files at the end of the parent_xml } } function SimpleXMLElementObj_into_xml($xml_parent, $xml_children, $linkingNode= "linkingNode" , $child_count = 0 , $xml = false ){ if(!$xml) { $xml = $xml_parent->addChild($linkingNode); }else{ $xml = $xml_parent[$child_count]; } $child_count = 0; foreach($xml_children->children() as $k => $v) { if($xml->$k){ $child_count++; } if($v->children()) { $xml->addChild($k); SimpleXMLElementObj_into_xml($xml->$k, $v, '', $child_count, true); }else{ $xml->addChild($k, $v); } } return $xml; } Thanks to some contributor whom I've taken the structure of this function. --was-- This function could be useful to somebody if you want to insert an XML into another when building an XML from many different files. Note that you must specify a name for the node in which the child files content/node will be inserted : foreach (xxx as $firstCondition){ $xml_parent = simplexml_load_file("$firstCondition.xml"); foreach (yyy as $secondCondition){ $xml_children = simplexml_load_file("secondCondition.xml"); SimpleXMLElementObj_into_xml($xml_parent , $xml_children , 'linkingNode'); //will insert every nodes of the files at the end of the parent_xml } } function SimpleXMLElementObj_into_xml($xml_parent, $xml_children, $linkingNode= "linkingNode" , $child_count = 0 , $xml = false ){ if(!$xml) { $xml = $xml_parent->addChild($linkingNode); }else{ $xml = $xml_parent[$child_count]; } $child_count = 0; foreach($xml_children->children() as $k => $v) { if($xml->$k){ $child_count++; } if($v->children()) { $xml->addChild($k); SimpleXMLElementObj_into_xml($xml->$k, $v, '', $child_count, true); }else{ $xml->addChild($k, $v); } } return $xml; } Thanks to some contributor whom I've taken the structure of this function. http://php.net/manual/en/ref.simplexml.php

« previous php.notes (#155509) next »