function SimpleXMLElement_append($key, $value) { // check class if (get_class($key) == 'SimpleXMLElement' && get_class($value) == 'SimpleXMLElement') { // check if the value is string value / data if (trim((string) $value) == '') { // add element and attributes $element = $key->addChild($value->getName()); foreach ($value->attributes() as $attKey => $attValue) { $element->addAttribute($attKey, $attValue); } // add children foreach ($value->children() as $child) { SimpleXMLElement_append($element, $child); } } else { // set the value of this item $element = $key->addChild($value->getName(), trim((string) $value)); } } else { // throw an error throw new Exception('Wrong type of input parameters, expected SimpleXMLElement'); } }
function SimpleXMLElement_append($parent, $child) { // get all namespaces for document $namespaces = $child->getNamespaces(true); // check if there is a default namespace for the current node $currentNs = $child->getNamespaces(); $defaultNs = count($currentNs) > 0 ? current($currentNs) : null; $prefix = count($currentNs) > 0 ? current(array_keys($currentNs)) : ''; $childName = strlen($prefix) > 1 ? $prefix . ':' . $child->getName() : $child->getName(); // check if the value is string value / data if (trim((string) $child) == '') { $element = $parent->addChild($childName, null, $defaultNs); } else { $element = $parent->addChild($childName, htmlspecialchars((string) $child), $defaultNs); } foreach ($child->attributes() as $attKey => $attValue) { $element->addAttribute($attKey, $attValue); } foreach ($namespaces as $nskey => $nsurl) { foreach ($child->attributes($nsurl) as $attKey => $attValue) { $element->addAttribute($nskey . ':' . $attKey, $attValue, $nsurl); } } // add children -- try with namespaces first, but default to all children // if no namespaced children are found. $children = 0; foreach ($namespaces as $nskey => $nsurl) { foreach ($child->children($nsurl) as $currChild) { SimpleXMLElement_append($element, $currChild); $children++; } } if ($children == 0) { foreach ($child->children() as $currChild) { SimpleXMLElement_append($element, $currChild); } } }