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
🌐
GitHub
github.com › spatie › array-to-xml
GitHub - spatie/array-to-xml: A simple class to convert an array to xml · GitHub
This package provides a very simple class to convert an array to an xml string.
Starred by 1.2K users
Forked by 214 users
Languages   PHP
🌐
Codementor
codementor.io › community › convert multidimensional array to xml file in php
Convert multidimensional array to XML file in PHP | Codementor
July 12, 2019 - For better understanding, all the Array to XML conversion code will be grouped together in a PHP function. The generateXML() function converts PHP multidimensional array to XML file format.
🌐
Matthias Kerstner
kerstner.at › home › blog › php – array to xml conversion
PHP - Array to XML Conversion - Matthias Kerstner
August 19, 2016 - $rootElement : '<root/>'); } foreach ($array as $k => $v) { if (is_array($v)) { //nested array arrayToXml($v, $k, $_xml->addChild($k)); } else { $_xml->addChild($k, $v); } } return $_xml->asXML(); }
🌐
PHP
php.net › manual › en › function.xml-parse-into-struct.php
PHP: xml_parse_into_struct - Manual
Below is an example that illustrates the internal structure of the arrays being generated by the function. We use a simple note tag embedded inside a para tag, and then we parse this and print out the structures generated: ... <?php $simple = "<para><note>simple note</note></para>"; $p = xml_parser_create(); xml_parse_into_struct($p, $simple, $vals, $index); echo "Index array\n"; print_r($index); echo "\nVals array\n"; print_r($vals); ?>
🌐
Wtools
wtools.io › convert-php-array-to-xml
Convert PHP Array to XML Online | WTOOLS
Free tool for online converting PHP array into XML document, generate XML from PHP array.
Find elsewhere
🌐
LIVEcommunity
live.paloaltonetworks.com › t5 › automation-api-discussions › php-xml-to-array › td-p › 20185
LIVEcommunity - PHP - XML to Array - LIVEcommunity - 20185
April 3, 2015 - So I've been working with the API pretty frequently and have run into a bit of a snag that has caught me now a few times. I'm using CURL with PHP to interact and whenever I get a response, I do a conversion as such: $xmlarr = json_decode(json_encode((array)simplexml_load_string($result)),1); This...
🌐
W3Schools
w3schools.com › php › func_xml_parse_into_struct.asp
PHP xml_parse_into_struct() Function
Index array - containing pointers to the location of the values in the Value array · xml_parse_into_struct(parser, data, values, index) ❮ PHP XML Parser Reference · ★ +1 · Sign in to track progress · REMOVE ADS · PLUS · SPACES · GET CERTIFIED · FOR TEACHERS ·
🌐
SitePoint
sitepoint.com › php
Array to xml - PHP - SitePoint Forums | Web Development & Design Community
December 17, 2014 - With simpleXML can you write a simple array to xml converter. Array may be associative but no need to xml attributes. Xml tag is array key and xml value of the tag is the value of array value. I did not understand how c…
🌐
GitHub
github.com › vyuldashev › xml-to-array
GitHub - vyuldashev/xml-to-array: A simple class to convert an xml to array
use Vyuldashev\XmlToArray\XmlToArray; $xml = '<items> <good_guy> <name>Luke Skywalker</name> <weapon>Lightsaber</weapon> </good_guy> <bad_guy> <name>Sauron</name> <weapon>Evil Eye</weapon> </bad_guy> </items>'; $result = XmlToArray::convert($xml); After running this piece of code $result will contain: array:1 [ "items" => array:2 [ "good_guy" => array:2 [ "name" => "Luke Skywalker" "weapon" => "Lightsaber" ] "bad_guy" => array:2 [ "name" => "Sauron" "weapon" => "Evil Eye" ] ] ]
Starred by 36 users
Forked by 15 users
Languages   PHP 100.0% | PHP 100.0%
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-convert-xml-file-into-array-in-php
How to convert XML file into array in PHP? - GeeksforGeeks
July 11, 2025 - json_decode() function: The json_decode() function is used to decode a JSON string. It converts a JSON encoded string into a PHP variable. Step 1: Creating an XML file (Optional): Create an XML file which need to convert into the array.
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 $key => $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.

🌐
SmallDev
smalldev.tools › xml-decoder-online
XML to array converter - SmallDev.tools
👍Convert any XML format to array format instantly. Fast, simple & secure. One click to copy & share output.
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-convert-array-to-simplexml-in-php
How to convert array to SimpleXML in PHP - GeeksforGeeks
May 10, 2023 - $xml = new SimpleXMLElement('<root/>'); // This function recursively added element // of array to xml document array_walk_recursive($my_array, array ($xml, 'addChild')); // This function prints xml document. print $xml->asXML(); ?> ... Note: ...
🌐
Wtools
wtools.io › convert-xml-to-php-array
Convert XML to PHP Array Online | WTOOLS
Convert PHP Array to XMLXML MinifierXML FormatterValidate XMLConvert XML to JSONXML Escape/UnescapeConvert XML to CSVConvert XML to TSVConvert XML to Plain TextConvert XML to ExcelConvert XML to HTML TableConvert XML to PDFConvert XML to SQLConvert XML to YAML
🌐
Adsar
adsar.co.uk › xml-to-array-php
XML to Arrays in PHP
function xml2array($xml, $flattenValues=true, $flattenAttributes = true, $flattenChildren=true, $valueKey='@value', $attributesKey='@attributes', $childrenKey='@children') { $return = array(); if (!($xml instanceof SimpleXMLElement)) { return $return; } $name = $xml->getName(); $_value = trim((string) $xml); if (strlen($_value) == 0) { $_value = null; }; if ($_value !== null) { if (!$flattenValues) { $return[$valueKey] = $_value; } else { $return = $_value; } } $children = array(); $first = true; foreach ($xml->children() as $elementName => $child) { $value = xml2array($child, $flattenValues,