<?php
/**
*
* @param array $in
* @param string $parentTag
* @param int $depth
* @return string
*/
function arrayToXml(array $in, $parentTag = 'root', $depth = 0)
{
$ret = '';
foreach ($in as $key => $value) {
$origKey = $key;
if (is_numeric($key)) {
$key = $parentTag;
}
if (is_array($value)) {
// Only append grouping tag if it has non-numeric children
$needsNewTagGroup = false;
foreach ($value as $testKey => $testValue) {
if (!is_numeric($testKey)) {
$needsNewTagGroup = true;
break;
}
}
if (is_numeric($origKey)) {
$needsNewTagGroup = true;
}
if ($needsNewTagGroup) {
$ret .= str_repeat(' ', $depth) . "<" . $key . ">\n";
$ret .= arrayToXml($value, $key, $depth + 1);
$ret .= str_repeat(' ', $depth) . "</" . $key . ">\n";
} else {
$ret .= arrayToXml($value, $key, $depth);
}
} else {
$ret .= str_repeat(' ', $depth) . "<" . $key . ">";
$ret .= str_replace(array('<', '>', '&'),
array('<', '>', '&'),
$value);
$ret .= "</" . $key . ">\n";
}
}
return $ret;
}
$tests[0]['input']['klasse'] = array(
'lehrer' => 'Fr. Müller',
'schuelerListe' => array(
'schueler' => array('Max', 'Moritz', 'Franzi', 'Paula')
),
);
$tests[0]['output'] = <<<EOT
<klasse>
<lehrer>Fr. Müller</lehrer>
<schuelerListe>
<schueler>Max</schueler>
<schueler>Moritz</schueler>
<schueler>Franzi</schueler>
<schueler>Paula</schueler>
</schuelerListe>
</klasse>
EOT;
$tests[1]['input'] = array('Max', 'Moritz', 'Franzi', 'Paula');
$tests[1]['output'] = <<<EOT
<root>Max</root>
<root>Moritz</root>
<root>Franzi</root>
<root>Paula</root>
EOT;
$tests[2]['input'] = array('Max', 'Moritz', array('Franzi', 'Peter'), 'Paula');
$tests[2]['output'] = <<<EOT
<root>Max</root>
<root>Moritz</root>
<root>
<root>Franzi</root>
<root>Peter</root>
</root>
<root>Paula</root>
EOT;
$tests[3]['input']['test'] = array(
'Max',
'Moritz',
'data' => array(
'names' => array(
'name' => array('Franzi', 'Peter')
),
'hello' => 'world'
),
'data2' => array('x', 'y', 'z'),
'Paula'
);
$tests[3]['output'] = <<<EOT
<test>
<test>Max</test>
<test>Moritz</test>
<data>
<names>
<name>Franzi</name>
<name>Peter</name>
</names>
<hello>world</hello>
</data>
<data2>x</data2>
<data2>y</data2>
<data2>z</data2>
<test>Paula</test>
</test>
EOT;
$tests[4]['input'] = array(
'characters' => array(
'character' => array(
array(
'name' => 'Gilles',
'class' => 'Archer'
),
array(
'name' => 'Johnny',
'class' => 'Knight'
)
)
)
);
$tests[4]['output'] = <<<EOT
<characters>
<character>
<name>Gilles</name>
<class>Archer</class>
</character>
<character>
<name>Johnny</name>
<class>Knight</class>
</character>
</characters>
EOT;
header('Content-Type: text/plain; charset=UTF-8');
// Run test suite
foreach ($tests as $index => $test) {
$a = $test['input'];
$xmlData = arrayToXml($a);
$xmlData = trim($xmlData);
if ($test['output'] !== $xmlData) {
printf("!!! TEST #%d FAILED\n\n", $index);
echo "Input:\n\n";
print_r($a);
echo "\n\nOutput:\n\n";
echo $xmlData;
echo "\n\nExpected:\n\n";
echo $test['output'];
} else {
printf("Test #%d passed\n\n", $index);
}
}