Hi devs,

I have a small challenge that I can't seem to solve or understand. Please give me some hints or advice.

In the code below I have an array with minimal data. When I run a recursive loop through the array it only prints the last child element in the array's hierarchy. If I use this same algorithm in Java for instance it works as expected but not in PHP...

PHP Code:
class ExportArrayToXML {
    
    var 
$file;
    var 
$handler;
    
    function 
__construct() {
        
$this->file "XML_DOC.xml";
        
$this->handler fopen($this->file'w') or die("can't open file");
        
        
$dataArray = array(
            
'root' => array( //only root and the last of it's child element is stored
                
'post' => 'POST_1',
                
'post' => 'POST_2',
                
'post' => 'POST_3' //only the last element is stored
            
)
        );

        
$this->exportToXML($dataArray);

        
fclose($this->handler);
    }
    
    function 
exportToXML($data) {
        if(
is_array($data)) {
            foreach(
$data as $element=>$key) {
                
fwrite($this->handler"<$element>");
                
                if(
is_array($key)) {
                    
$this->exportToXML($key);
                } else {
                    
fwrite($this->handler$key);
                }
                
                
fwrite($this->handler"<$element>");
            }
        } else {
            
fwrite($this->handler$data);
        }
    }
}

$eatx = new ExportArrayToXML(); 
The results in the saved file is as follows:

<root><post>POST_3<post><root>

I expect it to be:

<root><post>POST_1<post><post>POST_2<post><post>POST_3<post><root>

I appreciate any assistance or feedback.