This function will allow you to create XML document with simple PHP array variable. Nodes are just stacked onto each other and naming it 'Attribute_XXX' will add atribute XXX to that parent node.

function to_xml(SimpleXMLElement $object, array $data)
{
    $attr = "Attribute_";
    foreach ($data as value) {
        if (is_array($value)) {
            $new_object = $object->addChild($key);
            to_xml($new_object, $value);
        } else {
            if(strpos(attr) !== false){
                $object->addAttribute(substr($key, strlen($attr)), $value);
            }else{
                $object->addChild(value);
            }
        }
    }
}

Usage:

$my_array = array (
    'TagN1' => array (
        'TagInsideOfIt' => array (
            'Atrribute_IDuser' => 'anything',
            'RegularTag' => 'whatever',
            'Address' => array(
                'Attribute_ID' => '111',
                'Attribute_key' => 'aaa',
                'Company' => 'Google Inc.'
            )
        )
    )
);

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

to_xml(my_array);

Header('Content-type: text/xml');
print($xml->asXML());
Answer from jezda159 on Stack Overflow
🌐
PHP
php.net › manual › en › simplexmlelement.attributes.php
PHP: SimpleXMLElement::attributes - Manual
<?php SimpleXMLElement Object ( [@attributes] => Array ( [id] => 55555 ) [text] => "hello world" ) ?> Then using a function <?php function xml_attribute($object, $attribute) { if(isset($object[$attribute])) return (string) $object[$attribute]; } ?> ...
🌐
GitHub
github.com › spatie › array-to-xml
GitHub - spatie/array-to-xml: A simple class to convert an array to xml · GitHub
$result = ArrayToXml::convert($array, 'customrootname', false); You can use a key named _attributes to add attributes to a node, and _value to specify the value.
Starred by 1.2K users
Forked by 214 users
Languages   PHP
🌐
GitHub
github.com › jmarceli › array2xml
GitHub - jmarceli/array2xml: Convert PHP array to XML with support for attributes and CDATA
$input = array('product' => array( '@id' => 7, 'name' => 'some string', 'seo' => 'some-string', 'ean' => '', 'producer' => array( 'name' => null, 'photo' => '1.png' ), 'stock' => 123, 'trackstock' => 0, 'new' => 0, 'pricewithoutvat' => 1111, 'price' => 1366.53, 'discountpricenetto' => null, 'discountprice' => null, 'vatvalue' => 23, 'currencysymbol' => 'PLN', '#description' => '', '#longdescription' => '', '#shortdescription' => '', 'category' => array( 'photo' => '1.png', 'name' => 'test3', ), 'staticattributes' => array( 'attributegroup' => array( 1 => array( '@name' => 'attributes group', '
Starred by 45 users
Forked by 24 users
Languages   PHP 100.0% | PHP 100.0%
🌐
Packagist
packagist.org › packages › spatie › array-to-xml
spatie/array-to-xml - Packagist
January 12, 2026 - $result = ArrayToXml::convert($array, 'customrootname', false); You can use a key named _attributes to add attributes to a node, and _value to specify the value.
🌐
PHPpot
phppot.com › php › array-to-xml-conversion-using-php
Array to XML Conversion using PHP - PHPpot
July 8, 2022 - ), array( 'title' => 'PHP RSS Feed Read and List', 'link' => 'https://phppot.com/php/php-simplexml-parser/', 'description' => 'simplexml_load_file() function is used for reading data from XML.'
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-convert-array-to-simplexml-in-php
How to convert array to SimpleXML in PHP - GeeksforGeeks
May 10, 2023 - function arrayToXml($array, $rootElement = null, $xml = null) { $_xml = $xml; // If there is no Root Element then insert root if ($_xml === null) { $_xml = new SimpleXMLElement($rootElement !== null ?
Find elsewhere
🌐
GitHub
github.com › Jeckerson › array2xml
GitHub - Jeckerson/array2xml: [PHP] - Array to XML
$array2xml->setElementsAttrs( array('ElementName' => array('AttributeName' => $attributeValue) )); Note that in this case all elements with specified names will have identical attribute names and values.
Starred by 32 users
Forked by 21 users
Languages   PHP 100.0% | PHP 100.0%
Top answer
1 of 16
426

Here is php 5.2 code which will convert array of any depth to xml document:

Array
(
    ['total_stud']=> 500
    [0] => Array
        (
            [student] => Array
                (
                    [id] => 1
                    [name] => abc
                    [address] => Array
                        (
                            [city]=>Pune
                            [zip]=>411006
                        )                       
                )
        )
    [1] => Array
        (
            [student] => Array
                (
                    [id] => 2
                    [name] => xyz
                    [address] => Array
                        (
                            [city]=>Mumbai
                            [zip]=>400906
                        )   
                )

        )
)

generated XML would be as:

<?xml version="1.0"?>
<student_info>
    <total_stud>500</total_stud>
    <student>
        <id>1</id>
        <name>abc</name>
        <address>
            <city>Pune</city>
            <zip>411006</zip>
        </address>
    </student>
    <student>
        <id>1</id>
        <name>abc</name>
        <address>
            <city>Mumbai</city>
            <zip>400906</zip>
        </address>
    </student>
</student_info>

PHP snippet

<?php
// function defination to convert array to xml
function array_to_xml( $data, &$xml_data ) {
    foreach( $data as value ) {
        if( is_array($value) ) {
            if( is_numeric($key) ){
                $key = 'item'.$key; //dealing with <0/>..<n/> issues
            }
            $subnode = $xml_data->addChild($key);
            array_to_xml($value, $subnode);
        } else {
            $xml_data->addChild("$key",htmlspecialchars("$value"));
        }
     }
}

// initializing or creating array
$data = array('total_stud' => 500);

// creating object of SimpleXMLElement
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');

// function call to convert array to xml
array_to_xml($data,$xml_data);

//saving generated xml file; 
$result = $xml_data->asXML('/file/path/name.xml');

?>

Documentation on SimpleXMLElement::asXML used in this snippet

2 of 16
227

a short one:

<?php

$test_array = array (
  'bla' => 'blub',
  'foo' => 'bar',
  'another_array' => array (
    'stack' => 'overflow',
  ),
);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();

results in

<?xml version="1.0"?>
<root>
  <blub>bla</blub>
  <bar>foo</bar>
  <overflow>stack</overflow>
</root>

keys and values are swapped - you could fix that with array_flip() before the array_walk. array_walk_recursive requires PHP 5. you could use array_walk instead, but you won't get 'stack' => 'overflow' in the xml then.

🌐
Alex's Blog
alex.blog › 2011 › 06 › 29 › easily-create-xml-in-php-using-a-data-array
Easily Create XML In PHP Using A Data Array | Alex's Blog
June 30, 2011 - An array such as that is easy to ... of each array and it’s the tag name of the element. attributes is an array of attributes for the element and value is the value....
🌐
Envato Tuts+
code.tutsplus.com › parse-xml-to-an-array-in-php-with-simplexml--cms-35529t
Parse XML to an Array in PHP With SimpleXML | Envato Tuts+
Read these tutorials to learn how to work with data in XML format. Use XML to manipulate data, and learn how to parse and validate XML documents. ... In this post, you'll learn how to parse XML into an array in PHP.
🌐
Stack Overflow
stackoverflow.com › questions › 1209604 › converting-a-php-array-to-xml › 44287956
Converting a PHP array to XML? - Stack Overflow
function xml_from_indexed_array($array, $parent, $name) { echo '<?xml version="1.0"?>', "\n"; echo "<$parent>\n"; foreach ($array as $element) { echo " <$name>\n"; foreach ($element as $child => $value) { echo " <$child>$value</$child>\n"; } echo " </$name>\n"; } echo "</$parent>\n"; } As you can see, this is pretty straight forward, just iterating over all elements. ... <?php $colors = array(); $colors[0]['id'] = 1; $colors[0]['color'] = 'blue'; $colors[1]['id'] = 2; $colors[1]['color'] = 'green'; xml_from_indexed_array($colors, 'colors', 'color');
🌐
sqlpey
sqlpey.com › php › php-array-to-xml-conversion
PHP: Convert PHP Arrays to XML with Nested Structures - …
July 25, 2025 - A popular method is to use special keys, such as those starting with @ (e.g., @attributes), to designate attributes. When processing the array, your conversion logic will identify these keys and apply their values as attributes to the corresponding XML elements.
🌐
GitHub
gist.github.com › 913394 › 19fc31d5fb6db24406f53e7693ef0fc4935f02b3
Convert a PHP array into XML file using SimpleXML · GitHub
April 26, 2015 - I've found almost, if not the same code, here: https://snipt.net/robertbanh/php-array-to-xml/ Copy link · I was having problems with this code when settings attributes on otherwise empty nodes eg:- I modified the code as below to resolve · if ( $attr_start === 0 ) { $attrs[ substr($i, 5) ] = $v; if(count($value) == 1) $value=""; else unset( $value[$i] ); } Copy link ·
🌐
W3Schools
w3schools.com › php › func_xml_parse_into_struct.asp
PHP xml_parse_into_struct() Function
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
🌐
Stack Overflow
stackoverflow.com › questions › 67345364 › how-to-add-attributes-in-array-to-xml-conversion-in-php
How to add attributes in array to XML conversion in PHP - Stack Overflow
$test_array = array( 'bla' => 'param', 'foo' => 'param', ); $xml = new SimpleXMLElement('<params/>'); foreach ($test_array as $key => $value) { $child = $xml->addChild($value, $key); $child->addAttribute('key','value'); } print_r($xml->asXML()); ...