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 call addChild to add array entries as child elements of the root XML element on the SimpleXML DOM object.

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);
        }
    }
}

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

to create the to_xml function.

In it, we use a foreach loop to loop through the $data array entries.

In the loop, we call $object->addChild to add the $key as the child element.

Then we call to_xml with $new_object and $value to recursively convert the keys to elements.

Otherwise, we call addChild to add the $key and $value.

Conclusion

To convert an array to SimpleXML with PHP, we can call addChild to add array entries as child elements of the root XML element on the SimpleXML DOM object.

Leave a Reply

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