From 3f90e93af12b62e6a02ea54f67a3105180664a96 Mon Sep 17 00:00:00 2001 From: Timothy J Warren Date: Fri, 27 Jan 2017 09:43:42 -0500 Subject: [PATCH] Get xml parsing working predictably --- src/API/XML.php | 46 +++++++++++++++++++++++++++++++++++++++---- tests/API/XMLTest.php | 8 ++++++++ 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/src/API/XML.php b/src/API/XML.php index e8148737..35ef99ee 100644 --- a/src/API/XML.php +++ b/src/API/XML.php @@ -179,15 +179,43 @@ class XML { for ($i = 0; $i < $length; $i++) { $el = $nodeList->item($i); + $current =& $root[$el->nodeName]; + + // It's a top level element! if (is_a($el->childNodes->item(0), 'DomText') || ( ! $el->hasChildNodes())) { - $root[$el->nodeName] = $el->textContent; + $current = $el->textContent; + continue; } - else + + // An empty value at the current root + if (is_null($current)) { - $root[$el->nodeName] = []; - static::childNodesToArray($root[$el->nodeName], $el->childNodes); + $current = []; + static::childNodesToArray($current, $el->childNodes); + continue; } + + $keys = array_keys($current); + + // Wrap the array in a containing array + // if there are only string keys + if ( ! is_numeric($keys[0])) + { + // But if there is only one key, don't wrap it in + // an array, just recurse to parse the child nodes + if (count($current) === 1) + { + static::childNodesToArray($current, $el->childNodes); + continue; + } + $current = [$current]; + } + + array_push($current, []); + $index = count($current) - 1; + + static::childNodesToArray($current[$index], $el->childNodes); } } @@ -203,7 +231,17 @@ class XML { { foreach($data as $key => $props) { + // 'Flatten' the array as you create the xml + if (is_numeric($key)) + { + foreach($props as $key => $props) + { + break; + } + } + $node = $dom->createElement($key); + if (is_array($props)) { static::arrayPropertiesToXmlNodes($dom, $node, $props); diff --git a/tests/API/XMLTest.php b/tests/API/XMLTest.php index b14d3f5b..12a1e724 100644 --- a/tests/API/XMLTest.php +++ b/tests/API/XMLTest.php @@ -9,6 +9,7 @@ class XMLTest extends TestCase { public function setUp() { + $this->malExport = file_get_contents(__DIR__ . '/../test_data/XML/MALExport.xml'); $this->xml = file_get_contents(__DIR__ . '/../test_data/XML/xmlTestFile.xml'); $this->expectedXml = file_get_contents(__DIR__ . '/../test_data/XML/minifiedXmlTestFile.xml'); @@ -43,6 +44,13 @@ class XMLTest extends TestCase { { $this->assertEquals($this->array, XML::toArray($this->xml)); } + + public function testMALExport() + { + $array = XML::toArray($this->malExport); + $this->assertEquals($array['myanimelist']['myinfo']['user_total_anime'], count($array['myanimelist']['anime'])); + // $this->assertEquals($array, XML::toArray($this->malExport)); + } public function testParse() {