Skip to content

Instantly share code, notes, and snippets.

@cklosowski
Last active January 5, 2017 22:09
Show Gist options
  • Save cklosowski/11393077 to your computer and use it in GitHub Desktop.
Save cklosowski/11393077 to your computer and use it in GitHub Desktop.
Recursive Array to XML
<?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 );
}
}
}
@scarstens
Copy link

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)

$sampleObject = new stdClass();
$sampleObject->property = array('Should be converted to array ','by Array 2 XML Function');
$arrayFourLevelsDeepWithObjects = array(
    1=>'handle numerical arrays',
    'Level_ONE_A' => 'Easy to parse',
    'Level_FOUR_BY_ONE' => array(//fails to load levels
        'Level_FOUR_BY_TWO' => array(
            'Object_Test_Is_Next'=>null,
            'oLevel_FOUR_BY_THREE_A_OBJECT_NESTED_IN_ARRAY'=>$sampleObject,
            'Level_FOUR_BY_THREE_B' => array(
                'Level_FOUR_BY_FOUR' => array(
                    'attribute_ONE'=>'blue',
                    'attribute_TWO'=>null,
                    'attribute_THREE'=>3,
                    'attribute_FOUR'=>'',
                    'attribute_FIVE'=>true,
                    'attribute_SIX'=>false
                )
            ),

        )
    ),
    'Level_ONE_B' => 'Easy to parse too',
    'HANDLE_NUMBERS_IN_ARRAYS_1'=>'Dont just crash, show this node',
    'Handle Spaces'=>'Dont just crash, show this node',//fails
    'Handle (parens)'=>'Dont just crash, show this node',//fails
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment