0

I'm trying to convert a multidimensional array to an XML file with SimpleXML. I followed instructions from this post: https://stackoverflow.com/a/5965940/3169412 with these edits: http://pastebin.com/pYuXQWee but I can't get a correct result.

array used:

$array = 
array(
'name' => 'xxx',
'chapter' => array(
    array(
    'title' => 'yyy',
    'slide' => 
        array(
        'header' => array('zzz','aaa'),
        'paragraph' => array('bbb','ccc')
        ),
        array(
            'header' => array('ddd'),
            'paragraph' => array('eee')
        )
    ),
    array(
        'title' => 'fff',
        'slide' => array(
            'header' => array('ggg'),
            'paragraph' => array('hhh')
        )
    )
    )
);

Preferred (needed) XML output: http://pastebin.com/HWWeDehK

I tried using different approaches to get the right nodes on the right place, but they all seemed to fail. Closest I got was using array_keys($values), but then I got a lot of double nodes, or nodes on the wrong place.

XMLresult right now: http://pastebin.com/L8LL5VVe

Community
  • 1
  • 1
lennert_h
  • 113
  • 12

2 Answers2

0
$array = 
array(
'name' => 'xxx',
'chapter' => array(
    array(
    'title' => 'yyy',
    'slide' => 
        array(
        'header' => array('zzz','aaa'),
        'paragraph' => array('bbb','ccc')
        ),
        array(
            'header' => array('ddd'),
            'paragraph' => array('eee')
        )
    ),
    array(
        'title' => 'fff',
        'slide' => array(
            'header' => array('ggg'),
            'paragraph' => array('hhh')
        )
    )
    )
);

$xml = new SimpleXMLElement("<?xml version=\"1.0\"?><course></course>");

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{
                $subnode = $xml->addChild("item$key");
                array_to_xml($value, $subnode);
            }
        }
        else {
            $xml->addChild("$key",htmlspecialchars("$value"));
        }
    }
};

array_to_xml($array, $xml);

$xml->asXML('file.xml');

The content in file.xml is exactly as you requested.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
0

With FluidXML you can generate XML from a PHP array and then import it in SimpleXML

$data = [ 'doc' => [
              'fruit' => 'orange',
              'cake'  => [
                   '@id' => '123', 
                   '@'   => 'tiramisu' ],
              [ 'pasta' => 'matriciana' ],
              [ 'pasta' => 'boscaiola'  ]
] ];

just like that

$doc       = fluidxml($data);
$simplexml = simplexml_import_dom($doc->dom());

// Done. ;)

https://github.com/servo-php/fluidxml

Daniele Orlando
  • 2,692
  • 3
  • 23
  • 26