I needed a function that quickly converts an xml with key/value pairs to an array.
for example:
<?xml version="1.0" encoding="UTF-8"?>
<test>
<key id="Array key #1" value="Value #1"/>
<key id="Array key #2" value="Value #2"/>
<key id="Dupe" value="Duplicate keys"/>
<key id="Dupe" value="create numeric arrays"/>
<key id="And another key">
<![CDATA[
Multiline
data
works
just
as
well.
]]>
</key>
<nested>
<key id="Nested key" value="Nested data works as well, but it still results in a 1 dimensional array."/>
</nested>
</test>
Results in the following array:
array(5) {
["Array key #1"]=>
string(8) "Value #1"
["Array key #2"]=>
string(8) "Value #2"
["Dupe"]=>
array(2) {
[0]=>
string(14) "Duplicate keys"
[1]=>
string(21) "create numeric arrays"
}
["And another key"]=>
string(49) "Multiline
data
works
just
as
well."
["Nested key"]=>
string(73) "Nested data works as well, but it still results in a 1 dimensional array."
}
Here's the code:
<?php
function xml2array($xml) {
$domDocument = new DOMDocument;
$domDocument->loadXML($xml);
$domXPath = new DOMXPath($domDocument);
$array = array();
foreach ($domXPath->query('//key') as $keyDOM) {
$id = $keyDOM->getAttribute('id');
$value = $keyDOM->hasAttribute('value') ? $keyDOM->getAttribute('value') : trim($keyDOM->textContent);
if (array_key_exists($id, $array)) {
if (is_array($array[$id])) {
$array[$id][] = $value;
} else {
$array[$id] = array($array[$id]);
$array[$id][] = $value;
}
} else {
$array[$id] = $value;
}
}
return $array;
}
?>