How to convert an array to SimpleXML with PHP?

Spread the love

Sometimes, we want to convert an array to SimpleXML with PHP.

In this article, we’ll look at how to convert an array to SimpleXML with PHP.

How to convert an array to SimpleXML with PHP?

To convert an array to SimpleXML with PHP, we can traverse the array to add the nodes.

For instance, we write

function to_xml(SimpleXMLElement $object, array $data)
{   
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            $new_object = $object->addChild($key);
            to_xml($new_object, $value);
        } else {
            if ($key != 0 && $key == (int) $key) {
                $key = "key_$key";
            }
            $object->addChild($key, $value);
        }   
    }   
}  

to loop through the $data array with a foreach loop.

Then we check if $value is an array with is_array.

If it is, then we call addchild to add the $key as an objecty and call to_xml to add the $value as values.

Otherwise, we convert the key to a string if it’s an integer and call addChild to do the samr thing.

Then we cal use it by writing

$xml = new SimpleXMLElement('<rootTag/>');
to_xml($xml, $my_array);

by creating a rootTag element and then populate our $my_array array content as children.

Conclusion

To convert an array to SimpleXML with PHP, we can traverse the array to add the nodes.

Leave a Reply

Your email address will not be published. Required fields are marked *