How can I convert an array to a SimpleXML object in PHP?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- Illegal to have multiple roots (start tag in epilo
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
Just a edit on a function above, when a key is numeric, add a prefix "key_"
I found all of the answers to use too much code. Here is an easy way to do it:
Then it's a simple matter of sending the array into the function, which uses recursion, so it will handle a multi-dimensional array:
Now $xml contains a beautiful XML object based on your array exactly how you wrote it.
I use a couple of functions that I wrote a while back to generate the xml to pass back and forth from PHP and jQuery etc... Neither use any additional frameworks just purely generates a string that can then be used with SimpleXML (or other framework)...
If it's useful to anyone, please use it :)
Love to all :)
Most of the above answers are correct. However, I came up with this answer which solves the array_walk_recursive compatibility issue and also the numerical keys problem. It also passed all the tests I made:
I have also added a test class for this which you may find useful:
I would have commented the second most voted answer, because it doesn't preserve structure and generates bad xml if there is numerically indexed inner arrays.
I developed my own version based on it, because I needed simple converter between json and xml regardless of the structure of data. My version preserves numeric key information and structure of the original array. It creates elements for the numerically indexed values by wrapping values to value -named elements with key-attribute that contains numerical key.
For example
array('test' => array(0 => 'some value', 1 => 'other'))
converts to
<test><value key="0">some value</value><value key="1">other</value></test>
My version of array_to_xml -function (hope it helps somebody :)