Reply to bad use of foreach() when building xml str from xml tree (source code provided here).

Your name:

Reply:


Posted by "Scott Fletcher" on 09/28/05 20:15

Need some help here... The script didn't turned out right, especially with
the <Message> tags... For your conveince, I posted the code of my work here
with a slim-down testcase...

--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 my_build_xml($xml_tree, $x)
{
global $xml_data;
$x++;

foreach($xml_tree as $key => $value)
{
if(is_array($value)) {
if ($x % 2 != 0) {
$xml_data .= str_repeat(" ",$x)."<".$key.">"."\r\n";
my_build_xml($value, $x);
$xml_data .= str_repeat(" ",$x)."</".$key.">"."\r\n";
} else {
my_build_xml($value, $x);
}
} else {
if ($x % 2 != 0) {
$xml_data .= str_repeat("
",$x)."<".$key.">".$value."</".$key.">"."\r\n";
}
}
}
}

my_build_xml($array, "0");

echo $xml_data;
--snip--

The response I got is this...

--snip--
<NEWSFEED>
<MESSAGE>
<COMMENT>
<VALUE>Comment #1</VALUE>
</COMMENT>
<COMMENT>
<VALUE>Comment #2</VALUE>
</COMMENT>

</MESSAGE>
</NEWSFEED>
--snip--

which is not correct. The original xml data was

--snip--
$xml_str = "<NewsFeed>";
$xml_str .= " <Message>";
$xml_str .= " <Comment>";
$xml_str .= " <![CDATA[Comment #1]]>";
$xml_str .= " </Comment>";
$xml_str .= " </Message>";
$xml_str .= " <Message>";
$xml_str .= " <Comment>";
$xml_str .= " <![CDATA[Comment #2]]>";
$xml_str .= " </Comment>";
$xml_str .= " </Message>";
$xml_str .= "</NewsFeed>";
--snip--

I'm not gonna sweat about the difference between CDATA and VALUE which is
not the point here. The point here is the <Message> tags are incorrect. It
showed that I'm not doing somethign right with the foreach() function...
Some help here will be greatly appreciated. Thanks...

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация