How to Convert XML Into Array in PHP?

27 June 2023 276 Reading time: 1 minute

The response values of some APIs are in XML format or we are faced with processing data such as product lists.
So how can we convert XML (SimpleXMLElement) format to Array format with PHP?

You can convert the value you get with SimpleXMLElement to normal Array format by using the php function below.

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)];
}

Similar articles