I'm trying to transform an array into an XML
My XML needs to have the following structure
<Products>
<Product name="TR-501">
<Descricao texto="55.180.198 / 46789771" />
<Detalhes>
<Variacao modelo="Palio" ano="2006" motor="1.0 FIRE 8V (FLEX)" />
</Detalhes>
</Product>
</Products>
To do the conversion I'm using the following function in php
// function defination to convert array to xml
function array_to_xml( $data, &$xml_data ) {
foreach( $data as $key => $value ) {
if( is_numeric($key) ){
$key = 'item'.$key; //dealing with <0/>..<n/> issues
}
if( is_array($value) ) {
$subnode = $xml_data->addChild($key);
array_to_xml($value, $subnode);
} else {
$xml_data->addChild("$key",htmlspecialchars("$value"));
}
}
}
and I'm getting the following return
<?xml version="1.0"?>
<Products>
<product>
<name>TR-501</name>
<description>55.180.198 / 46789771</description>
<detalhes>
<variacao>
<item0>
<modelo>Palio</modelo>
<ano>2006</ano>
<motor>1.0 FIRE 8V (FLEX)</motor>
</item0>
<item1>
<modelo>Palio</modelo>
<ano>2006</ano>
<motor>1.0 FIRE 8V (FLEX)</motor>
</item1>
<item2>
<modelo>Palio</modelo>
<ano>2006</ano>
<motor>1.0 FIRE 8V (FLEX)</motor>
</item2>
</variacao>
</detalhes>
</product>
</Products>
How can I do so that I can get multiple rows of relative data inside instead of <item0> <item1> <item2>
?
Note: the way the data is displayed inside the items, whether it's property or content of the tags is irrelevant, it's only relevant that I can get several lines of <variacao>
different without <item0> <item1>
. Ex:
<Variacao modelo="Palio" ano="2006" motor="1.0 FIRE 8V (FLEX)" />
<Variacao modelo="Palio" ano="2001/2004" motor="1.0 FIRE 8V (FLEX)" />
<Variacao modelo="Palio" ano="2003/2006" motor="1.3 FIRE 8V" />