How to convert array to SimpleXML

How to convert array to SimpleXML

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Converting Arrays to SimpleXML in PHP

Converting an array to a SimpleXMLElement object is a common requirement when dealing with legacy data formats or when you need to manipulate XML structures dynamically without writing raw strings. While PHP provides native functions for this, the approach depends heavily on the structure of your input array and whether you are working within a modern framework like Laravel. The most direct method utilizes the SimpleXMLElement::fromXML() constructor overload introduced in PHP 8.2, but pre-8.2 environments or more complex data structures require manual string construction followed by parsing.

Using SimpleXMLElement::fromXML()

If you are running PHP 8.2 or later, the standard library offers a convenient static method to handle this conversion directly. You can pass an array containing associative keys and values, or even nested arrays, and it will attempt to construct a valid XML structure.

$data = [
    'name' => 'John Doe',
    'age' => 30,
    'roles' => ['Admin', 'Editor'],
    'settings' => [
        'theme' => 'dark',
        'notifications' => true
    ]
];

$xml = SimpleXMLElement::fromXML($data);

This method is efficient for simple hierarchical data. However, it has strict limitations regarding the resulting structure. The output will strictly represent the array as an element map, where keys become child elements of the root node created by the function call. If your array contains numeric keys or null values in specific positions that do not align with a valid XML tree, fromXML() may throw an exception or generate unexpected empty nodes.

Manual String Construction for Compatibility

For environments prior to PHP 8.2, or when you need finer control over the root element name and attributes, converting the array to a string first is the most reliable approach. You can leverage json_encode with specific options to create a JSON representation, then use simplexml_load_string. This works because SimpleXML supports loading from strings that are valid XML, and there is a known behavior where certain JSON structures can be interpreted as XML if wrapped correctly, though this is often brittle.

A more robust manual method involves constructing an actual XML string using DOMDocument or DOMElement, then converting that DOM object to a SimpleXML instance. This ensures you have full control over namespaces, attributes, and text content.

function arrayToSimpleXML(array $data, string $rootName = 'root'): ?SimpleXMLElement {
    // Create a DOM document
    $dom = new DOMDocument('1.0', 'UTF-8');
    
    // Create the root element
    $root = $dom->createElement($rootName);
    $dom->appendChild($root);

    // Helper function to recursively add elements
    $addElement = function ($parent, $key, $value) use (&$addElement) {
        $element = $parent->ownerDocument->createElement($key);
        
        if (is_array($value)) {
            foreach ($value as $subKey => $subValue) {
                // Handle nested arrays or simple values within the loop
                // Logic to distinguish between object-like arrays and simple lists goes here
                if (is_numeric(array_search($subKey, array_keys($value)))) {
                    // Treat as list of items
                    $item = $element->appendChild($parent->ownerDocument->createElement('item'));
                    $item->appendChild($parent->ownerDocument->createTextNode((string)$subValue));
                } else {
                    // Treat as associative object
                    $addElement($element, $subKey, $subValue);
                }
            }
        } else {
            $root->setAttribute($key, (string)$value);
            // Or simply add the key/value pair to the root if structure allows
            // Note: SimpleXML usually expects elements, not attributes for top-level keys unless specified.
            // A common pattern is to treat the first level as children of a specific node or attributes.
        }
    };

    // Correct recursive approach for flat associative arrays into children
    $children = [];
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            // Determine if it's an object-like structure or a list
            $firstKey = array_key_first($value);
            if (is_numeric($firstKey)) {
                // It's a list, create multiple items
                $item = $dom->createElement('item');
                foreach ($value as $v) {
                    $childItem = $dom->createElement('item');
                    $childItem->appendChild($dom->createTextNode((string)$v));
                    $children[] = $childItem;
                }
            } else {
                // It's an object, create one element with children
                $objElement = $dom->createElement($key);
                foreach ($value as $subKey => $subValue) {
                    $subElement = $dom->createElement($subKey);
                    $subElement->appendChild($dom->createTextNode((string)$subValue));
                    $objElement->appendChild($subElement);
                }
                $children[] = $objElement;
            }
        } else {
            // Simple attribute or child depending on desired XML shape
            // Often best to make them children for simplicity in SimpleXML
            $child = $dom->createElement($key);
            $child->appendChild($dom->createTextNode((string)$value));
            $children[] = $child;
        }
    }

    foreach ($children as $child) {
        $root->appendChild($child);
    }

    $dom->appendChild($root);
    
    // Convert to SimpleXML
    return simplexml_import_dom($dom);
}

The logic above handles nested arrays by checking if the first key is numeric (indicating a list) or string (indicating an object). This distinction is crucial because SimpleXML does not automatically infer list structures from associative arrays without explicit element creation.

Trade-offs and Framework Integration

When working within the Laravel ecosystem, you might consider whether native PHP classes are the best fit for your use case. While converting to SimpleXMLElement allows you to cast nodes to arrays using (array)$xml->child, it introduces a layer of indirection that can be cumbersome if you only need XML serialization capabilities.

If your primary goal is simply to generate an XML response from an array, Laravel's built-in helpers or the XmlSitemapGenerator package might offer cleaner alternatives. However, if you must interact with an external API that strictly requires a SimpleXMLElement instance for validation, the manual DOM approach ensures compatibility across different PHP versions. Always remember that casting between objects and arrays loses type information; once converted to SimpleXML, you are working with nodes, not native PHP variables, which affects how you perform operations like sorting or filtering unless you cast back immediately.

Our network