PHP中的递归问题

str*_*ade 1 php xml recursion

我需要从给定的数组()创建一个有效的xml;

我的方法看起来像这样,

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;
    }
Run Code Online (Sandbox Code Playgroud)

如果我执行上面的操作,我只需要获取空值的键;

喜欢

<node>
<name></name>
</node>
Run Code Online (Sandbox Code Playgroud)

如果我通过这个,我需要的是什么 array("name"=>"test","value"=>array("test1"=>33,"test2"=>40));

它返回这个

<node>
<name>test</name>
<value>
<test1>33</test1>
<test2>40</test2>
</value>
</node>
Run Code Online (Sandbox Code Playgroud)

错误在哪里错误在上面的递归中我错了什么?

nic*_*ckf 5

你忘了"别的":

 if(is_array($value)) {
      $xml .= $this->array2Xml($value);
 } else {
      $xml .= $value;
 }
Run Code Online (Sandbox Code Playgroud)