I want to take an xml file, break it down and save it to a db while preserving its hierarchy using the nested set model. I have converted the xml to an array using the following function. Is there a way to modify this function to add left and right values? Or a way to go through the result and add left and right values while collapsing the array?
<?php
function xml_to_array($root) {
$result = array();
$disallowed = Array('#text','#comment');
if ($root->hasAttributes()) {
$attrs = $root->attributes;
foreach ($attrs as $attr) {
$result['@attributes'][$attr->name] = $attr->value;
}
}
if ($root->hasChildNodes()) {
$children = $root->childNodes;
if ($children->length == 1) {
$child = $children->item(0);
if ($child->nodeType == XML_TEXT_NODE) {
$result['_value'] = $child->nodeValue;
return count($result) == 1
? $result['_value']
: $result;
}
}
$groups = array();
foreach ($children as $child) {
if (!in_array($child->nodeName , $disallowed) ){
if (!isset($result[$child->nodeName])) {
$result[$child->nodeName] = xml_to_array($child);
} else {
if (!isset($groups[$child->nodeName])) {
$result[$child->nodeName] = array($result[$child->nodeName]);
$groups[$child->nodeName] = 1;
}
$result[$child->nodeName][] = xml_to_array($child);
}
}
}
}
return $result;
}
?>
Sample xml: note- every node has attributes. I would like to save the left/right under the attribute array.
<root>
<nodeFoo>
<nodeBar>
<nodeXYZ/>
<nodeXYZ/>
<nodeXYZ/>
</nodeBar>
</nodeFoo>
<nodeBar>
<nodeXYZ/>
<nodeXYZ/>
<nodeXYZ/>
</nodeBar>
</root>
No comments:
Post a Comment