Categories
PHP

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


By Moazzam

Moazzam is a software developer working in the big apple. He has over a decade of experience in development. While most of his work involves developing web applications, he does development for Android and Windows Mobile in his spare time.

2 replies on “Convert an array to XML in PHP”

Leave a Reply

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