Recursion Problem in PHP
Posted
by streetparade
on Stack Overflow
See other posts from Stack Overflow
or by streetparade
Published on 2010-04-22T13:34:39Z
Indexed on
2010/04/22
13:43 UTC
Read the original article
Hit count: 196
I need to create a valid xml from a given array();
My Method looks like this,
protected function array2Xml($array)
{
$xml = "";
if(is_array($array))
{
foreach($array as $key=>$value)
{
$xml .= "<$key>";
if(is_array($value))
{
$xml .= $this->array2Xml($value);
}
$xml .= "</$key>";
}
return $xml;
}
else
{
throw new Exception("in valid");
}
}
protected function createValidXMLfromArray($array,$node)
{
$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$xmlArray = $this->array2Xml($array);
$xml .= "<$node>$xmlArray</$node>";
return $xml;
}
if i execute the above i just get keys with empty values;
like
<node>
<name></name>
</node>
What i need is if i pass this array("name"=>"test","value"=>array("test1"=>33,"test2"=>40));
that it return this
<node>
<name>test</name>
<value>
<test1>33</test1>
<test2>40</test2>
</value>
</node>
Where is the error what did i wrong in the above recursion?
© Stack Overflow or respective owner