Skip to content

Commit 834840e

Browse files
z38sebastianbergmann
authored andcommitted
Fix duplicated keys in nested XML array
1 parent 9d99dce commit 834840e

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

src/Util/XML.php

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -222,17 +222,20 @@ public static function xmlToVariable(DOMElement $element)
222222
case 'array':
223223
$variable = array();
224224

225-
foreach ($element->getElementsByTagName('element') as $element) {
226-
$item = $element->childNodes->item(0);
225+
foreach ($element->childNodes as $entry) {
226+
if (!$entry instanceof DOMElement || $entry->tagName !== 'element') {
227+
continue;
228+
}
229+
$item = $entry->childNodes->item(0);
227230

228231
if ($item instanceof DOMText) {
229-
$item = $element->childNodes->item(1);
232+
$item = $entry->childNodes->item(1);
230233
}
231234

232235
$value = self::xmlToVariable($item);
233236

234-
if ($element->hasAttribute('key')) {
235-
$variable[(string) $element->getAttribute('key')] = $value;
237+
if ($entry->hasAttribute('key')) {
238+
$variable[(string) $entry->getAttribute('key')] = $value;
236239
} else {
237240
$variable[] = $value;
238241
}

tests/Util/XMLTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,4 +342,22 @@ public function testLoadBoolean()
342342
{
343343
PHPUnit_Util_XML::load(false);
344344
}
345+
346+
public function testNestedXmlToVariable()
347+
{
348+
$xml = '<array><element key="a"><array><element key="b"><string>foo</string></element></array></element><element key="c"><string>bar</string></element></array>';
349+
$dom = new DOMDocument();
350+
$dom->loadXML($xml);
351+
352+
$expected = [
353+
'a' => [
354+
'b' => 'foo',
355+
],
356+
'c' => 'bar',
357+
];
358+
359+
$actual = PHPUnit_Util_XML::xmlToVariable($dom->documentElement);
360+
361+
$this->assertSame($expected, $actual);
362+
}
345363
}

0 commit comments

Comments
 (0)