0

I am working on a RESTful API serving content in three modes viz., JSON [most of the times], HTML [when non-api calls are made] and XML [legacy support].

My controllers return PHP arrays and then in the Views, I convert them into the desired output. PHP to JSON is done via json_encode, PHP to HTML is done via message passing between Views and Template Engine. Now, I am writing a recursive function to handle multi-dimensional PHP arrays and convert them into well formatted XML.

Following is my function:

function recursive_xml($array, \SimpleXMLElement $xmlObj){
    foreach($array as $key=>$value){
        $xmlObj->addChild($key);
        if(!is_array($value)){
            $xmlObj->$key = $value;
        }
        else { //Value is array
            recursive_xml($value, $xmlObj->$key);
        }
    }
    header('Content-type: text/xml');
    echo $xmlObj->asXML();
} //End recursive_xml

This is working almost 80% as expected, going through arrays and creating the XML output. But the funny problem is that in the second call of the recursive_xml and there after, it appends the output in the XML and ALSO before the XML decalaration. Let's take a test case:

$obj = new \SimpleXMLElement("<root />");
$array = array("a"=>"b", "c"=>"d", "e"=>array("x"=>"z", "y"=>"v")); 
recursive_xml($array, $obj);

Now the output:

 `<e><x>z</x><y>v</y></e><?xml version="1.0"?>
 <root><a>b</a><c>d</c><e><x>z</x><y>v</y></e></root>`

The second line of the output along with the XML declaration is what I would be ideally looking for. Any help will be deeply appreciated!

1 Answer 1

1

I will not try to understand what exactly is going on there.

Yet i can tell you that your problem is your call to echo. Try returning your SimpleXMLElement from your function in a proper way and asXML() and echo it from outside the function and it will work as expected :)

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! Thanks a lot. Am in the middle of a marathon session here, been programming straight for around 90 hours :) The wife is threatening to leave me... you are a life savior @Alexander!
You are welcome. 90 hours sounds unhealty. Hope you calculated the money for some presents for her when the big bucks hit your pocket ;)

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.