Skip to content

Instantly share code, notes, and snippets.

@hakre
Created January 3, 2013 17:15
Show Gist options
  • Save hakre/4445046 to your computer and use it in GitHub Desktop.
Save hakre/4445046 to your computer and use it in GitHub Desktop.
<?php
/**
* php array to xml conversion even for nested data
*
* @link http://stackoverflow.com/q/14136714/367456
* @see http://stackoverflow.com/a/14143759/367456 for description
* @author hakre <http://hakre.wordpress.com/credits>
*/
$array = [
'name' => 'ABC',
'email' => '[email protected]',
'phones' =>
[
'phone' =>
[
[
'mobile' => '9000199193',
'land' => ' 9999999 ',
],
[
'mobile' => '9000199193',
'land' => ' 9999999 ',
],
[
'mobile' => '9000199194',
'land' => ' 5555555 ',
],
[
'mobile' => '9000199195',
'land' => ' 8888888 ',
],
],
],
];
$createArrayImporter = function (SimpleXMLElement $subject) {
$add = function (SimpleXMLElement $subject, $key, $value) use (&$add) {
$hasKey = is_string($key);
$isString = is_string($value);
$isArray = is_array($value);
$count = count($value);
$isIndexed = $isArray && $count > 1 && array_keys($value) === range(0, $count - 1);
$isKeyed = $isArray && $count && !$isIndexed;
switch (true) {
case $isString && $hasKey:
return $subject->addChild($key, $value);
case $isIndexed && $hasKey:
foreach ($value as $oneof_value) {
$add($subject, $key, $oneof_value);
}
return $subject->$key;
case $isKeyed && $hasKey:
$subject = $subject->addChild($key);
// fall-through intended
case $isKeyed:
foreach ($value as $oneof_key => $oneof_value) {
$add($subject, $oneof_key, $oneof_value);
}
return true;
default:
trigger_error('Unknown Nodetype ' . print_r($value, 1));
}
};
return function (Array $array) use ($subject, $add) {
$add($subject, null, $array);
return $subject;
};
};
# require('inc/simplexml_pretty_print.php');
/**
* @param SimpleXMLElement $SimpleXML
* @return string
* @link http://stackoverflow.com/a/798986/367456
*/
function simplexml_pretty_print(SimpleXMLElement $SimpleXML) {
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($SimpleXML->asXML());
return $dom->saveXML();
}
$xml = new SimpleXMLElement('<root/>');
$importer = $createArrayImporter($xml);
echo simplexml_pretty_print($importer($array));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment