grueb
grueb

Reputation: 133

multi-dimensional PHP array with mixed integer and string keys to XML

I am trying to convert a PHP array to valid XML. The problem I have is that the array has nested arrays with integer keys and I want them to belong to the same XML tag.

Using an array_to_xml function I found on stackoverflow helped me with the conversion, but converts the nested arrays with integer keys to invalid and unwanted xml keys like <0>< /0>.

Here the example code:

$array = array(test1 => 1, test2 => 2, test3 => array("a", "b", "c"));

$xml = new SimpleXMLElement('<parameters></parameters>');
array_to_xml($array, $xml);

$result = $xml -> asXML("test.xml");

which generates:

<?xml version="1.0"?>
  <parameters>
    <test1>1</test1>
    <test2>2</test2>
    <test3><0>a</0><1>b</1><2>c</2></test3>
</parameters>

However, I need it to look like:

<?xml version="1.0"?>
  <parameters>
    <test1>1</test1>
    <test2>2</test2>
    <test3>a</test3>
    <test3>b</test3>
    <test3>c</test3>
</parameters>

Is there an easy way to convert such a PHP array and generate the above XML structure?

P.S.: I use the following array_to_xml function:

function array_to_xml($array, &$xml) {

    foreach($array as $key => $value) {
        if(is_array($value)) {
            if(!is_numeric($key)){              
                $subnode = $xml->addChild("$key");
                array_to_xml($value, $subnode);
            } else {                
                array_to_xml($value, $xml);
            }
        } else {            
            $xml->addChild("$key","$value");
        }
    }
}

Upvotes: 0

Views: 796

Answers (1)

John Mc Murray
John Mc Murray

Reputation: 363

how about this:

// http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
function isAssoc(array $arr)
{
    if (array() === $arr) return false;
    return array_keys($arr) !== range(0, count($arr) - 1);
}

function array_to_xml($array, &$xml)
{

    foreach($array as $key => $value)
    {
        if(is_array($value))
        {
            if(isAssoc($value))
            {
                $Parent = $xml->addChild($key);
                foreach($value as $childKey => $childValue)
                {
                    $Parent->addChild($childKey, $childValue);
                }
            }
            else
            {
                foreach($value as $subvalue)
                 {
                    $xml->addChild("$key","$subvalue");
                 }
            }
        }
        else
        {
            $xml->addChild("$key","$value");
        }
    }
}

John...

Upvotes: 1

Related Questions