KillerFish
KillerFish

Reputation: 5170

PHP XML Writer not generating xml if node name is same

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

Upvotes: 0

Views: 546

Answers (2)

Riddhi Kanji
Riddhi Kanji

Reputation: 11

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(.....)
)

Upvotes: 1

Marko
Marko

Reputation: 512

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.

Upvotes: 1

Related Questions