Created
February 5, 2019 17:15
-
-
Save Bunnyfield/3f62a2d436b63cb5e65ddacf466a108d to your computer and use it in GitHub Desktop.
Convert XML to Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function convertXmlObjToArr(\SimpleXMLElement $node) : array | |
{ | |
$element = [ | |
'@name' => strtolower((string)$node->getName()), | |
'@attributes' => [] | |
]; | |
$attributes = $node->attributes(); | |
foreach ($attributes as $attributeName => $attributeValue) | |
{ | |
$attribName = strtolower(trim((string)$attributeName)); | |
$attribVal = trim((string)$attributeValue); | |
$element['@attributes'][$attribName] = $attribVal; | |
} | |
$text = \trim((string)$node); | |
if (\strlen($text) > 0) { | |
$element['@text'] = $text; | |
} | |
if ($node->children()) { | |
$childrenList = $node->children(); | |
foreach ($childrenList as $elementName => $node) | |
{ | |
$element[$elementName][] = $this->convertXmlObjToArr($node); | |
} | |
} | |
return $element; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment