Re: bad use of foreach() when building xml str from xml tree (source code provided here).
| From: | Jochem Maas | Date: | Wed, 28 Sep 2005 19:45:43 +0000 |
| Subject: | Re: bad use of foreach() when building xml str from xml tree (source code provided here). | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-223380@lists.php.net to get a copy of this message | ||
Scott Fletcher wrote:
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'
)
)
)
)
)
)
);
that array is structurally the same as the first
output xml - I would say the function seems to work..
wat do you get when you stuff this thru your function:
$array = array('NEWSFEED' => array(
'0' => array(
'MESSAGE' => array(
'0' => array(
'COMMENT' => array(
'0' => array(
'VALUE' => 'Comment #1')))),
'1' => array(
'MESSAGE' => array(
'0' => array(
'COMMENT' => array(
'0' => array(
'VALUE' => 'Comment #2'))))
)));
function my_build_xml($xml_tree, $x) {how did you transform the xml data into an array?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...