Forked from Bunnyfield/gist:3f62a2d436b63cb5e65ddacf466a108d
Created
February 6, 2019 20:11
-
-
Save briezler/409b18f8beaef82a1f58c8fd71336339 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