How to Convert Array to XML in PHP?


In PHP, you can convert an array to XML using various methods. One common approach is utilizing the `SimpleXMLElement` class to build an XML structure from the array. Here's an example:

// Sample array

$arrayData = [

    'person' => [

        'name' => 'John Doe',

        'age' => 30,

        'email' => '',


    'address' => [

        'street' => '123 Main St',

        'city' => 'Anytown',

        'country' => 'USA',



// Function to convert array to XML

function arrayToXml($array, $xml = null) {

    if ($xml === null) {

        $xml = new SimpleXMLElement('<root/>');


    foreach ($array as $key => $value) {

        if (is_array($value)) {

            // If the value is an array, recursively call the function

            arrayToXml($value, $xml->addChild($key));

        } else {

            // If it's a single value, add it as a child element

            $xml->addChild($key, htmlspecialchars($value));



    return $xml->asXML();


// Convert the array to XML

$xmlString = arrayToXml($arrayData);

// Output the generated XML

echo $xmlString;


- The function `arrayToXml()` takes an array as input and recursively converts it into an XML structure using `SimpleXMLElement`.

- If the value in the array is also an array, the function calls itself recursively to create nested XML elements.

- `htmlspecialchars()` is used to handle special characters to ensure they're properly represented in XML.

This code snippet will generate XML based on the array structure provided. Adjust the array structure and keys according to the data you want to convert to XML.