Skip to content

Instantly share code, notes, and snippets.

@Bunnyfield
Created February 5, 2019 17:15
Show Gist options
  • Save Bunnyfield/3f62a2d436b63cb5e65ddacf466a108d to your computer and use it in GitHub Desktop.
Save Bunnyfield/3f62a2d436b63cb5e65ddacf466a108d to your computer and use it in GitHub Desktop.
Convert XML to Array
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