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 ); }
// 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); } } }
The BIGGEST differece between an XML and a PHP array is that in an XML file, the name of elements can be the same even if they are siblings, eg. "", while in an PHP array, the key of which must be different.
I think the array structure developed by svdmeer can fit for XML, and fits well.
here is an example array converted from an xml file: array( "@tag"=>"name", "@attr"=>array( "id"=>"1","class"=>"2") "@text"=>"some text", )