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?
With FluidXML you can generate, starting from a PHP Array, an XML for SimpleXML with... just two lines of code.
An example array could be
https://github.com/servo-php/fluidxml
You can Use the following function in you code directly,
Call the function with first argument as your array and the second argument must be 1, this will be increased for perfect indentation, and third must be true.
for example, if the array variable to be converted is $array1 then, calling would be, the calling function should be encapsulated with
<pre>
tag.Please see the page source after executing the file, because the < and > symbols won't be displayed in a html page.
My answer, cobbling together others' answers. This should correct for the failure to compensate for numeric keys:
The
array_to_xml()
function presumes that the array is made up of numeric keys first. If your array had an initial element, you would drop theforeach()
and$elem
statements from thearray_to_xml()
function and just pass$xml
instead.Whole XML structure is defined in $data Array:
The answers provided here only convert array to XML with nodes, you are not able to set attributes. I have written a php function that allows you to convert an array to php and also set attributes for particular nodes in the xml. The downside here is you have to construct an array in a particular way with few conventions (only if you want to use attributes)
The following example will allow you to set attributes in XML too.
Detailed example and usage can be found here: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes/
Based on everything else here, handles numerical indices + attributes via prefixing with
@
, and could inject xml to existing nodes:Code
Usage
Result
Bonus: Formatting XML