Re: bad use of foreach() when building xml str from xml tree(source code provided here).
| From: | Scott Fletcher | Date: | Wed, 28 Sep 2005 21:43:50 +0000 |
| Subject: | Re: bad use of foreach() when building xml str from xml tree(source code provided here). | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-223385@lists.php.net to get a copy of this message | ||
Here's we go. A better script here. Now I only need to figure out how to
add data to the string and assigned it to string 1 when done. I used hte
break command there to make a point here. Maybe this will work...
--snip--
$array = array
(
'NEWSFEED' => array
(
'0' => array
(
'MESSAGE' => array
(
'0' => array
(
'COMMENT' => array
(
'0' => array
(
'VALUE' => 'Comment #1'
)
)
),
'1' => array
(
'COMMENT' => array
(
'0' => array
(
'VALUE' => 'Comment #2'
)
)
)
)
)
)
);
function GetXmlStr($tree)
{
$branch_level = 0; //Tree's branches level...
XmlTreeDecompile($tree, $branch_level, $str1, $str2, $str3);
//echo $str1." #<br>";
//echo $str2." #<br>";
//echo $str3." #<br>";
return htmlentities($str1.$str2.$str3);
}
function XmlTreeDecompile($tree, $branch_level, &$str1, &$str2, &$str3)
{
$branch_level++;
foreach($tree as $key => $value)
{
if ($branch_level % 2 != 0) { //xml name-tag counter...
if(!(is_array($value))) {
$str2 .= str_repeat("
",$branch_level)."<".$key.">".$value."</".$key.">"."\r\n";
} else {
$str1 .= str_repeat("
",$branch_level)."<".$key.">"."\r\n";
XmlTreeDecompile($value, $branch_level, $str1, $str2, $str3);
$str3 .= str_repeat("
",$branch_level)."</".$key.">"."\r\n";
}
} else { //Xml tag's name...
//echo $key." #<br>";
if ($key != 0) {
break;
//$str1 .= $str2;
//$str2 = "";
}
XmlTreeDecompile($value, $branch_level, $str1, $str2, $str3);
}
}
echo $str1." \n--\n";
echo $str2." \n--\n";
echo $str3." \n--\n";
}
$xml_string = GetXmlStr($array);
echo "\n<br><br>\n".$xml_string;
--snip--