Can someone help with converting data from an XML document to an associative array? I run into problems considering that the XML structure is a kind of 3D, and the array is larger than the 2D structure (please forgive my lack of proper terminology). The XML elements have attributes, children and grandchildren (but I never know their names), so I decided that I would try to make the key in the array a concatenation of each child / attribute name and value equal to, Value. The problem is that I need the attribute name and value as part of the key of the concatenated array 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>
Ideally, you should 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 get 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 the [Computer-id] key is not unique. I use a recursive function to read values, but I canβt figure out how to get the attribute name and attribute value in the name of subordinate keys ... (By the way, there is a good reason for this, it would seem an illogical task!) Any help would be greatly appreciated .. .
Here is a function that βsmoothesβ XML data after it has been read in a multidimensional array. I'm not sure I'm going to do it right!
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"; } } }
Jak
source share