How can I convert an array to a SimpleXML object in PHP?
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.
The source can be found here: https://github.com/digitickets/lalit/blob/master/src/Array2XML.php
array(
'type' => 'fiction'
),
'book' => array(
array(
'@attributes' => array(
'author' => 'George Orwell'
),
'title' => '1984'
),
array(
'@attributes' => array(
'author' => 'Isaac Asimov'
),
'title' => 'Foundation',
'price' => '$15.61'
),
array(
'@attributes' => array(
'author' => 'Robert A Heinlein'
),
'title' => 'Stranger in a Strange Land',
'price' => array(
'@attributes' => array(
'discount' => '10%'
),
'@value' => '$18.00'
)
)
)
);
/* creates
1984
Foundation
$15.61
Stranger in a Strange Land
$18.00
*/
?>