1
I’m trying to turn 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 make the conversion I am 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 feedback
<?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 make it so that I can get multiple rows of with the relative data in instead of <item0> <item1> <item2>
?
Note: the way the data is displayed inside the items, whether by property or content of the tags is irrelevant, it is relevant only 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" />
Hello Peter, I tested using your implementation, but the problem persists the same, I can not generate two lines of <Variacao> with different values
– Ariel conti
There seems to be something strange about this Else
} else {
 $xml_data->appendChild(new DOMElement($key, $value));
}– Ariel conti
I made a correction and changed the answer to show an example with "two lines of <Variation> with different values". The code can be tested on: https://3v4l.org/BquYA
– Pedro Amaral Couto
Good Peter! It worked!
– Ariel conti