Is there any more elegant way to escape SimpleXML attributes to an array?
$result = $xml->xpath( $xpath );
$element = $result[ 0 ];
$attributes = (array)
For me below method worked
function xmlToArray(SimpleXMLElement $xml)
{
$parser = function (SimpleXMLElement $xml, array $collection = []) use (&$parser) {
$nodes = $xml->children();
$attributes = $xml->attributes();
if (0 !== count($attributes)) {
foreach ($attributes as $attrName => $attrValue) {
$collection['@attributes'][$attrName] = strval($attrValue);
}
}
if (0 === $nodes->count()) {
if($xml->attributes())
{
$collection['value'] = strval($xml);
}
else
{
$collection = strval($xml);
}
return $collection;
}
foreach ($nodes as $nodeName => $nodeValue) {
if (count($nodeValue->xpath('../' . $nodeName)) < 2) {
$collection[$nodeName] = $parser($nodeValue);
continue;
}
$collection[$nodeName][] = $parser($nodeValue);
}
return $collection;
};
return [
$xml->getName() => $parser($xml)
];
}
This also provides me all the attributes as well, which I didn't get from any other method.