vellai durai
vellai durai

Reputation: 1011

array2xml conversion in php

I need to convert array to XML, everything is working fine but when numeric value comes it is difficult to convert

function array2XML($obj, $array)
{
    foreach ($array as $key => $value)
    {
        if(is_numeric($key))
            $key = 'item' . $key;

        if (is_array($value))
        {
            $node = $obj->addChild($key);
            array2XML($node, $value);
        }
        else
        {
            $obj->addChild($key, htmlspecialchars($value));
        }
    }


}

I need to have previous key if numeric value exists

here is my json data

 {"aaa":"111","bbb":222,"ccc":{"abc":[{"aaa":"123","bbb":253,"ccc":147},{"aaa":"123","bbb":253,"ccc":147}]},"bbc":{"bcc":[{"aaa":"1222","dfg":"123","vfbh":741},{"aaa":"1222","dfg":"123","vfbh":741}]}}

here is my created XML

     <aaa>111<aaa>
        <bbb>222</bbb>
         <ccc>
          <abc>
          <item0>
         <aaa></aaa>
         <bbb></bbb>
         <ccc></ccc>
</item0>
 <item1>
         <aaa></aaa>
         <bbb></bbb>
         <ccc></ccc>
</item1>

But i need item0 to be prevoius key for ex in this case

Here is what i expect

<aaa>111<aaa>
            <bbb>222</bbb>
             <ccc>

              <abc>
             <aaa></aaa>
             <bbb></bbb>
             <ccc></ccc>
    </abc>
     <abc>
             <aaa></aaa>
             <bbb></bbb>
             <ccc></ccc>
    </abc>

Upvotes: 0

Views: 912

Answers (1)

unixmiah
unixmiah

Reputation: 3153

<?php

$test_array = array (
  'bla' => 'blub',
  'foo' => 'bar',
  'another_array' => array (
    'stack' => 'overflow',
  ),
);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();
results in

<?xml version="1.0"?>
<root>
  <blub>bla</blub>
  <bar>foo</bar>
  <overflow>stack</overflow>
</root>

You shouldn't have any issues with numeric values.

Upvotes: 1

Related Questions