How can an array be built recursively from an XML file in PHP?

To build an array recursively from an XML file in PHP, you can use the SimpleXMLElement class to parse the XML file and convert it into an array. You can then iterate over the XML elements and build the array recursively by checking for child nodes and adding them as nested arrays.

function xmlToArray($xml) {
    $array = [];
    
    foreach ($xml->children() as $child) {
        $name = $child->getName();
        $data = (count($child->children()) === 0) ? (string) $child : xmlToArray($child);
        
        if (!isset($array[$name])) {
            $array[$name] = $data;
        } else {
            if (!is_array($array[$name]) || !array_key_exists(0, $array[$name])) {
                $array[$name] = [$array[$name]];
            }
            $array[$name][] = $data;
        }
    }
    
    return $array;
}

$xml = simplexml_load_file('data.xml');
$array = xmlToArray($xml);

print_r($array);