Last active
January 5, 2017 22:09
-
-
Save cklosowski/11393077 to your computer and use it in GitHub Desktop.
Recursive Array to XML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$test_array = array ( | |
'bla' => 'blub', | |
'another_array' => array('stack' => 'overflow'), | |
'foo' => 'bar', | |
'this' => array( 'this_item' => 'that' ) | |
); | |
$xml = new SimpleXMLElement('<root/>'); | |
foreach ( $test_array as $key => $value ) { // Itterate through the array and pass to our custom fucntion | |
ck_add_child( $xml, $key, $value ); | |
} | |
print $xml->asXML(); | |
function ck_add_child( $element, $key, $value ) { | |
if ( !is_array( $value ) ) { // If the value of this item is not an array, add it as a child of the root node | |
$element->addChild( $key, $value ); | |
} else { // If the item is another array, split it out and itterate through it until all items are added to this new node, then return to normal business | |
$nested = $element->addChild( $key ); | |
foreach ( $value as $key2 => $value2 ) { | |
ck_add_child( $nested, $key2, $value2 ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is my "unit test" for the function/class. Expects a function "build_xml" with 2 params. First param is the data array, the second is the default name for a node (used when nodes cannot be labled due to numeric or other issues in parsing)