Here is a more namespace-aware version of the earlier function for attaching one SimpleXMLElement to another. I'm sure it could still be further improved (right now it generates some redundant xmlns definitions), but it seems to be working well enough for my purposes so far.
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);
}
}
}