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

Answer from Hanmant on Stack Overflow
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.

🌐
Wtools
wtools.io › convert-php-array-to-xml
Convert PHP Array to XML Online - wtools.io
Free tool for online converting PHP array into XML document, generate XML from PHP array.

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

Answer from Hanmant on Stack Overflow
🌐
PHP
php.net › manual › en › book.simplexml.php
PHP: SimpleXML - Manual
If you tried to load an XML file with this, but the CDATA parts were not loaded for some reason, is because you should do it this way: $xml = simplexml_load_file($this->filename, 'SimpleXMLElement', LIBXML_NOCDATA); This converts CDATA to String ...
🌐
PHPpot
phppot.com › php › array-to-xml-conversion-using-php
Array to XML Conversion using PHP - PHPpot
July 8, 2022 - XML nodes <title>, <link> and <description> is created for each item to store the array data and the nodes are added to the XML document. After converting PHP array to an XML document, I saved it as a file in the specified target.
🌐
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.
🌐
GitHub
github.com › spatie › array-to-xml
GitHub - spatie/array-to-xml: A simple class to convert an array to xml · GitHub
You can use the constructor to set DOMDocument properties. $result = ArrayToXml::convert( $array, $rootElement, $replaceSpacesByUnderScoresInKeyNames, $xmlEncoding, $xmlVersion, ['formatOutput' => true] );
Starred by 1.2K users
Forked by 214 users
Languages   PHP
🌐
CodexWorld
codexworld.com › home › convert array to xml in php
Convert array to XML in PHP - CodexWorld
June 2, 2017 - You can easily generate XML file from PHP array and save the XML file. You can convert all types of array like Associative array or Multidimensional arrays. At first we will store the users data into a variable ($users_array). $users_array = array( "total_users" => 3, "users" => array( array( "id" => 1, "name" => "Smith", "address" => array( "country" => "United Kingdom", "city" => "London", "zip" => 56789, ) ), array( "id" => 2, "name" => "John", "address" => array( "country" => "USA", "city" => "Newyork", "zip" => "NY1234", ) ), array( "id" => 3, "name" => "Viktor", "address" => array( "country" => "Australia", "city" => "Sydney", "zip" => 123456, ) ), ) );
Find elsewhere
🌐
CodexWorld
codexworld.com › home › convert array to xml and xml to array in php
Convert Array to XML and XML to Array in PHP - CodexWorld
November 27, 2017 - Convert PHP Array to XML File - Read XML file and convert XML to array in PHP. Example code to convert array to XML and XML to array in PHP.
🌐
Matthias Kerstner
kerstner.at › home › blog › php – array to xml conversion
PHP - Array to XML Conversion - Matthias Kerstner
August 19, 2016 - $rootElement if specified will ... of $array */ function arrayToXml($array, $rootElement = null, $xml = null) { $_xml = $xml; if ($_xml === null) { $_xml = new SimpleXMLElement($rootElement !== null ?...
🌐
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: ...
🌐
Vantulder
vantulder.net › old-articles › array-to-xml
Array to XML function for PHP | Gijs van Tulder
<?xml version="1.0" encoding="ISO-8859-1"?> <array> <file> myfile </file> <file> yourfile </file> <user> <name> Foo </name> </user> <user> <name> Bar </name> </user> <time> <day> tuesday </day> <week> 23 </week> </time> </array> function array_to_xml($array, $level=1) { $xml = ''; if ($level==1) { $xml .= '<?xml version="1.0" encoding="ISO-8859-1"?>'. "\n<array>\n"; } foreach ($array as $key=>$value) { $key = strtolower($key); if (is_array($value)) { $multi_tags = false; foreach($value as $key2=>$value2) { if (is_array($value2)) { $xml .= str_repeat("\t",$level)."<$key>\n"; $xml .= array_to_xml($value2, $level+1); $xml .= str_repeat("\t",$level)."</$key>\n"; $multi_tags = true; } else { if (trim($value2)!='') { if (htmlspecialchars($value2)!=$value2) { $xml .= str_repeat("\t",$level).
🌐
Yifan-online
yifan-online.com › en › km › article › detail › 14731
Please explain how to convert an array to XML using PHP and provide a sample code. | yifan-online web service yifan
Converting arrays to XML using PHP can be handled using PHP's built-in DOMDocument class. Code exam | The leading AIGC tool testing field to help you grow and improve
🌐
Kodytools
kodytools.com › php-array-to-xml-converter
PHP Array to XML Converter Online | Kody Tools
Convert PHP Array to XML online using our free online PHP Array to XML converter tool.
🌐
Table Convert
tableconvert.com › home › convert xml to php array online
Convert XML to PHP Array Online - Table Convert
January 11, 2019 - The tool automatically parses XML structure and converts it to table format, supporting namespace, attribute handling, and complex nested structures. ... Edit data using our advanced online table editor with professional features. Supports deleting empty rows, removing duplicates, data transposition, sorting, regex find & replace, and real-time preview. All changes automatically convert to PHP format with precise, reliable results. ... Generate standard PHP array code that can be directly used in PHP projects, supporting associative and indexed array formats.
🌐
Wtools
wtools.io › convert-xml-to-php-array
Convert XML to PHP Array Online - wtools.io
array ( 'result' => array ( 'website' => array ( 'domain' => 'wtools.io', 'title' => 'Online Web Tools', ), ), ) After the conversion, you can apply the PHP array to your project or use it for some other purpose. ... Did you like this tool? You can donate to us. This will help us improve our free web tools. Paypal ... 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
🌐
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 › timkippdev › php-array-to-xml-converter
GitHub - timkippdev/php-array-to-xml-converter: PHP library to convert an array of data to XML
use TimKippDev\ArrayToXmlConverter\ArrayToXmlConverter; ... $data = [ 'foo' => 'bar' ]; $xml = ArrayToXmlConverter::convert($data, [ 'encoding' => 'ISO-8859-15', // default - "UTF-8" 'formatOutput' => true, // default - true 'rootName' => ...
Author   timkippdev
🌐
Web20university
web20university.com › posts › convert-array-to-xml-in-php
Convert an Array to XML in PHP (with examples) - Web 2.0 University
July 16, 2024 - XMLWriter: A built-in PHP extension for creating XML documents. Spatie Array to XML: A popular package available via Composer.
🌐
Packagist
packagist.org › packages › spatie › array-to-xml
spatie/array-to-xml - Packagist
January 12, 2026 - For a full list of valid properties ... constructor to set DOMDocument properties. $result = ArrayToXml::convert( $array, $rootElement, $replaceSpacesByUnderScoresInKeyNames, $xmlEncoding, $xmlVersion, ['formatOutput' => true] );...