Convert an array to XML in PHP

I haven’t benchmarked the memory consumption of this method versus just traversing the array yourself and writing XML but I can’t see anything else being more efficient than this.

$testArray = [
    'key1' => 'val1',
    'key2' => [
        'key3' => 'hello'
    ]
];

$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($testArray, array ($xml, 'addChild'));
print $xml->asXML();



Posted

in

by

Tags:

Comments

2 responses to “Convert an array to XML in PHP”

  1. Daniel White Avatar
    Daniel White

    Yeah, this is wrong, clearly untested. Try it yourself.

  2. admin Avatar
    admin

    Thanks for pointing that out Daniel. I fixed the code

Leave a Reply

Your email address will not be published. Required fields are marked *