Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to convert array to SimpleXML

How can I convert an array to a SimpleXML object in PHP?
by

1 Answer

vishaljlf39
<?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>


keys and values are swapped - you could fix that with array_flip() before the array_walk. array_walk_recursive requires PHP 5. you could use array_walk instead, but you won't get 'stack' => 'overflow' in the xml then.

Login / Signup to Answer the Question.