Can anyone help with converting data from an XML document into an associative array? I'm running into issues given that the XML structure is sort of 3D and the array is more of a 2D structure (please forgive my lack of correct terminology throughout). The XML elements have attributes, children and grand-children (but I never know their names), so I figured I'd try to make the key in the array a concatenation of each child/attribute name and the value equal to, well, the value. Trouble is I need the attribute name and value as part of the concatenated array key to make it unique...
For example:
<Computer id="1">
<OS>
<Name>Linux</Name>
<Age>Older than me</Age>
</OS>
</Computer>
<Computer id="2">
<OS>
<Name>Windows</Name>
<Age>Not so much</Age>
</OS>
</Computer>
Should ideally give:
[Computer-id-1-OS-Name] = 'Linux'
[Computer-id-1-OS-Age] = 'Older than me'
[Computer-id-2-OS-Name] = 'Windows'
[Computer-id-2-OS-Age] = 'Not so much'
But I'm getting this result:
[Computer-id] = '1'
[Computer-OS-Name] = 'Linux'
[Computer-OS-Age] = 'Older than me'
[Computer-id] = '2'
[Computer-OS-Name] = 'Windows'
[Computer-OS-Age] = 'Not so much'
So that the [Computer-id] key is not unique. I'm using a recursive function to read in the values, but I can't figure how to get the attribute name and attribute value into the name of the subordinate keys...(By the way there is a good reason for doing this seemingly illogical task!) Any help would be greatly appreciated...
Here is the function which 'flattens' the XML data after it has been read into a multi-dimensional array. I'm not sure I'm going about this the right way!
function flattenArray ($array, $baseName = NULL)
{
reset($array);
while (list ($key, $value) = each($array)) {
$outKey = $key . "-";
if (is_array($value)) {
flattenArray($value, $baseName . $outKey);
} else {
$finalKey = $baseName . rtrim($outKey, '-');
$finalValue = $value;
echo "$finalKey = $finalValue\n";
}
}
}