1

How can I convert the following nested array into xml file? What will the XML file look like?

Array(
array('name'=>'Jone Smith','phone'=>'416-689-9865'),
array('name'=>'Jane    Ling','phone'=>'658-985-5222')
);
1

1 Answer 1

3
<?php
$your_array= array ('key1' => 'val1', 'key2' => 'val2', 'second_array' => array ('key3' => 'val3','key4' => 'val4'),);
$toXml = new SimpleXMLElement('<root/>');
array_walk_recursive($your_array, array ($toXml, 'addChild'));
print_r($toXml->asXML());

Other alternate is to use array_walk. The array_walk_recursive() function runs each array element in a user-made function. The array's keys and values are parameters in the function. The difference between this function and the array_walk() function is that with this function you can work with deeper arrays (an array inside an array)

Sign up to request clarification or add additional context in comments.

1 Comment

This is a rather clever solution, but it breaks when a value is empty. Not sure why though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.