How to Convert arrays or SimpleXML-Objects into an XML-String
Posted
by streetparade
on Stack Overflow
See other posts from Stack Overflow
or by streetparade
Published on 2010-03-27T21:25:38Z
Indexed on
2010/03/27
21:33 UTC
Read the original article
Hit count: 273
I want to create a xml from a given string, i have a function but i didn't wrote it.It seems a bit cryptical too. Can please some one review it and give me some Ideas, how it could be written clearer for everybody?
/**
* Converts arrays or SimpleXML-Objects into an XML-String
* @params mixed Accepts an array or xml string with data to Post
* @params integer DO NOT PROVIDE. Internal Usage for recursion only
*/
private function mixedDataToXML($data, $level = 1)
{
if(!$data){
return FALSE;
}
if(is_array($data)) {
$xml = '';
if ($level==1) {
$xml .= '<?xml version="1.0" encoding="ISO-8859-1"?>'."\n";
}
foreach ($data as $key => $value) {
$key = strtolower($key);
if (is_array($value)) {
$multi_tags = false;
foreach($value as $key2=>$value2) {
if (is_array($value2)) {
$xml .= str_repeat("\t",$level)."<$key>\n";
$xml .= $this->mixedDataToXML($value2, $level+1);
$xml .= str_repeat("\t",$level)."</$key>\n";
$multi_tags = true;
} else {
if (trim($value2)!='') {
if (htmlspecialchars($value2)!=$value2) {
$xml .= str_repeat("\t",$level).
"<$key><![CDATA[$value2]]>".
"</$key>\n";
} else {
$xml .= str_repeat("\t",$level).
"<$key>$value2</$key>\n";
}
}
$multi_tags = true;
}
}
if (!$multi_tags and count($value)>0) {
$xml .= str_repeat("\t",$level)."<$key>\n";
$xml .= $this->mixedDataToXML($value, $level+1);
$xml .= str_repeat("\t",$level)."</$key>\n";
}
} else {
if (trim($value)!='') {
if (htmlspecialchars($value)!=$value) {
$xml .= str_repeat("\t",$level)."<$key>".
"<![CDATA[$value]]></$key>\n";
} else {
$xml .= str_repeat("\t",$level).
"<$key>$value</$key>\n";
}
}
}
}
return $xml;
}else{
return (string)$data;
}
}
© Stack Overflow or respective owner