The developing was really straightforward, and the performance is not that bad.
Watch it here.
Only tested it on Chrome, not sure it will work on other browsers.
Video credits to Benny Benassi.
// Example structure
$obj = new stdClass();
$obj->prop1 = 'hello';
$obj->prop2 = new stdClass();
$obj->prop2->prop2 = 'there';
$obj->prop2->prop3 = 'world!';
/**
*
* @param stdClass $obj
* @return array
*/
function flatr($obj) {
$ret = array();
$recursiveWalk = function( $baseObject ) use (&$recursiveWalk, &$ret) {
if (is_object($baseObject)) {
foreach($baseObject as $propValue) $recursiveWalk($propValue);
} else {
$ret[] = $baseObject;
}
};
$recursiveWalk($obj);
return $ret;
}
var_dump(flatr($obj));
/**
*
* @param StdClass $obj
* @param string $baseName
* @return string
*/
function object2xml($obj, $baseName) {
$ret = '<' . $baseName . ">\n";
$recursiveWalk = function( $baseObject, $level ) use (&$recursiveWalk) {
$recRet = '';
foreach($baseObject as $k => $child) {
$next = $recursiveWalk($child, $level + 1);
if ($next === '') {
$recRet .= str_repeat(' ', $level * 4) . '<' . $k . "/>\n";
} else {
$recRet .= str_repeat(' ', $level * 4) . '<' . $k . ">\n" . $next;
$recRet .= str_repeat(' ', $level * 4) . ' . $k . ">\n";
}
}
return $recRet;
};
$ret .= $recursiveWalk($obj, 1);
return $ret . " . $baseName . ">\n";
}
?>The example usage for this code follows:
$obj = (object) array(
'level1_1' => (object) array(
'level2_1' => (object) array(
'level3_1' => (object) array(
),
'level3_2' => (object) array(
)
),
'level2_2' => (object) array(
)
)
);
print object2xml($obj, 'root');
?>