Array to DOM
Here is a recursive function to turn a multidimensional array into an XML document. It will handle multiple elements of the same tag, but only one per parent element. IE:
Can't generate: Can generate:
<root> <root>
<sub1>data1</sub1> <subs1>
<sub1>data2</sub1> <value>data1</value>
<sub2>data1</sub2> <value>data2</value>
<sub2>data2</sub2> </subs1>
</root> <subs2>
<value>data1</value>
<value>data2</value>
<subs2>
</root>
Also, the function performs no type of error checking on your array and will throw a DOMException if a key value you used in your array contains invalid characters for a proper DOM tag. This function is untested for "deep" multidimensional arrays.
Complete code ready to run with example:
<?PHP
function AtoX($array, $DOM=null, $root=null){
if($DOM == null){$DOM = new DOMDocument('1.0', 'iso-8859-1');}
if($root == null){$root = $DOM->appendChild($DOM->createElement('root'));}
$name = $array['#MULTIPLE_ELEMENT_NAME'];
foreach($array as $key => $value){
if(is_int($key) && $name != null){
if(is_array($value)){
$subroot = $root->appendChild($DOM->createElement($name));
AtoX($value, $DOM, $subroot);
}
else if(is_scalar($value)){
$root->appendChild($DOM->createElement($name, $value));
}
}
else if(is_string($key) && $key != '#MULTIPLE_ELEMENT_NAME'){
if(is_array($value)){
$subroot = $root->appendChild($DOM->createElement($key));
AtoX($value, $DOM, $subroot);
}
else if(is_scalar($value)){
$root->appendChild($DOM->createElement($key, $value));
}
}
}
return $DOM;
}
$array = array(
'#MULTIPLE_ELEMENT_NAME' => 'GenericDatas',
'Date' => 'November 03, 2007',
'Company' => 'Facility One',
'Field' => 'Facility Management Software',
'Employees' => array(
'#MULTIPLE_ELEMENT_NAME' => 'Employee',
'Cindy',
'Sean',
'Joe',
'Owen',
'Jim',
'Dale',
'Kelly',
'Ryan',
'Johnathan',
'Robin',
'William Marcus',
'NewCoops' => array(
'#MULTIPLE_ELEMENT_NAME' => 'Coop',
'John',
'Tyler',
'Ray',
'Dawn'
)
),
'Datas',
'DATAS',
'OtherDatas'
);
$DOM = new DOMDocument('1.0', 'iso-8859-1');
$root = $DOM->appendChild($DOM->createElement('CompanyData'));
$DOM = AtoX($array, $DOM, $root);
$DOM->save('C:\test.xml');
?>