1

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?

2

4 Answers 4

5

You forgot the "else":

 if(is_array($value)) {
      $xml .= $this->array2Xml($value);
 } else {
      $xml .= $value;
 }
Sign up to request clarification or add additional context in comments.

2 Comments

I dont know why but i get epty nodes
@streetparade: how is this any different to dereleased's answer which worked?
3

You never placed the values into the code; your recursion is OK, you just missed the all-important step of supplying the data. Try this on for size:

protected function array2Xml($array)
    {
        $xml = "";

        if(is_array($array))
        {
            foreach($array as $key=>$value)
            {
                $xml .= "<$key>";

                if(is_array($value))
                {
                    $xml .= $this->array2Xml($value);
                }
                else {
                    $xml .= $value;
                }
                $xml .= "</$key>\n";
            }

            return $xml;
        }
        else
        {
            throw new Exception("in valid");
        }
    }

Comments

2

Maybe

if(is_array($value))
{
 $xml .= $this->array2Xml($value);
}
else
{
 $xml .= $value;
}

?

Comments

1

you are missing one thing, after your check if $value is array you need to add else else $xml .= $value;

if you know what I mean

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.