0
votes

I am trying to generte xml data from Associate array.

My array is

$data = array(
    'item' => array(
        'id' => '1',
        'name' => 'bar1',
        'price' => '10',
        'description' => '',
        'image_link_small' => '',
        'image_link_big' => ''
    ),
    'item' => array(
        'id' => '2',
        'name' => 'bar2',
        'price' => '20',
        'description' => '',
        'image_link_small' => '',
        'image_link_big' => ''
    ),
    'item' => array(
        'id' => '3',
        'name' => 'bar3',
        'price' => '30',
        'description' => '',
        'image_link_small' => '',
        'image_link_big' => ''
    ),
    'item' => array(
        'id' => '4',
        'name' => 'bar4',
        'price' => '40',
        'description' => '',
        'image_link_small' => 'link1',
        'image_link_big' => 'link2'
    )
);

My php array to xml converter code is

public function convertArrayToXML($data, $rootElement = 'root', $startDoc = '1.0', $xml_encoding = 'UTF-8') {
        $xml = new XmlWriter();
        $xml->openMemory();
        $xml->startDocument($startDoc, $xml_encoding);
        $xml->startElement($rootElement);

        function write(XMLWriter $xml, $data) {
            foreach ($data as $key => $value) {
                if (is_array($value)) {
                    $xml->startElement($key);
                    write($xml, $value);
                    $xml->endElement();
                    continue;
                }
                $xml->writeElement($key, $value);
            }
        }

        write($xml, $data);

        $xml->endElement();
        return $xml->outputMemory(true);
    }

But it is giving me output xml only last node ...

<root>
<item>
<id>4</id>
<name>bar4</name>
<price>40</price>
<description/>
<image_link_small>link1</image_link_small>
<image_link_big>link2</image_link_big>
</item>
</root>

If i change the item in array to item1, item2, item3, item4 it is giving me correct xml data. what might be the problem?

Thank You

2
The conversion to XML is doing exactly what it is supposed to do with the data you are giving it. Try dumping your array immediately after you have defined it. You will find that each element overwrites the element before it, since each element has the same name, leaving only the last element.Jason

2 Answers

1
votes

This is not a XML writer problem. Try

var_dump($data);

You will see the problem. You can't have the same key several times in an PHP array.

1
votes

In $data array key values are same, that's why first three values are overwritten by last value.try something like :

$data = array(
  'item1' => array(.....),
  'item2' => array(.....),
  'item2' => array(.....)
)