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
🌐
GitHub
github.com › spatie › array-to-xml
GitHub - spatie/array-to-xml: A simple class to convert an array to xml · GitHub
Call $arrayToXml->prettify() method on ArrayToXml to set XML in pretty form.
Starred by 1.2K users
Forked by 214 users
Languages   PHP
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.

🌐
Codementor
codementor.io › community › convert multidimensional array to xml file in php
Convert multidimensional array to XML file in PHP | Codementor
July 12, 2019 - The data array needs to be passed as a parameter in generateXML() function. This function creates an XML document using DOMDocument class and inserts the PHP array content in this XML document.
🌐
Laracasts
laracasts.com › discuss › channels › laravel › array2xml
Laracasts
We cannot provide a description for this page right now
🌐
Mtvbrianking
mtvbrianking.github.io › laravel-xml › master › Bmatovu › LaravelXml › Support › ArrayToXml.html
Bmatovu\LaravelXml\Support\ArrayToXml | Laravel XML
convert(array $arr, string $rootElementName = 'document', bool $replaceSpacesByUnderScoresInKeyNames = true, string $xmlEncoding = 'UTF-8', string $xmlVersion = '1.0') Convert the given array to an xml string.
Find elsewhere
🌐
PHPpot
phppot.com › php › array-to-xml-conversion-using-php
Array to XML Conversion using PHP - PHPpot
July 8, 2022 - This code has the input array structure supplied to the PHP foreach loop to iterate the inner array elements. Before iterating the input array, I have created an object for the DOMDocument() class. This object is used to create the XML document.
🌐
The Coding Dev
thecodingdev.com › home › convert array to xml in php › how to convert array to xml in php?
How to Convert Array to XML in PHP?
December 10, 2023 - Laravel · Javascript · DSA and ... to XML using various methods. One common approach is utilizing the `SimpleXMLElement` class to build an XML structure from the array....
🌐
Packagist
packagist.org › packages › mtownsend › xml-to-array
mtownsend/xml-to-array - Packagist.org
$xml = <<<XML <?xml version="1.0"?> <request> <carrier>fedex</carrier> <id>123</id> <tracking_number>9205590164917312751089</tracking_number> </request> XML; $array = xml_to_array($xml); // $array is: [ 'carrier' => 'fedex', 'id' => '123', 'tracking_number' => '9205590164917312751089' ];
🌐
CodexWorld
codexworld.com › home › convert array to xml in php
Convert array to XML in PHP - CodexWorld
June 2, 2017 - Array to XML conversion in PHP - Convert array to XML using PHP SimpleXML. Simple script for convert PHP associative array to 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 - The above problem can be solved using array_walk_recursive() function. This function converts array to xml document where keys of array are converted into values and values of array are converted into element of XML.
🌐
ItSolutionstuff
itsolutionstuff.com › post › how-to-convert-array-to-xml-in-phpexample.html
How to Convert Array to XML in PHP? - ItSolutionstuff.com
May 14, 2024 - The "arrayToXml" function recursively converts the array to XML using the `SimpleXMLElement` class. Finally, it prints the XML using `echo`. If you want to save the XML to a file, you can use the `$xml->asXML('output.xml');` line instead of ...
🌐
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); ?>
🌐
GitHub
github.com › spatie › array-to-xml › blob › main › src › ArrayToXml.php
array-to-xml/src/ArrayToXml.php at main · spatie/array-to-xml
$array, $rootElement, $replaceSpacesByUnderScoresInKeyNames, $xmlEncoding, $xmlVersion, $domProperties, $xmlStandalone, $addXmlDeclaration, $options · ); · return $converter->toXml(); } ·
Author   spatie