PHP 8.5.0 Alpha 4 available for testing

Voting

: one minus one?
(Example: nine)

The Note You're Voting On

CameronXie
7 years ago
Map xml to array (with attributes)

<?php declare(strict_types=1);

/**
* @param SimpleXMLElement $xml
* @return array
*/
function xmlToArray(SimpleXMLElement $xml): array
{
$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()) {
$collection['value'] = 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)
];
}

<< Back to user notes page

To Top