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.

🌐
Laracasts
laracasts.com › discuss › channels › laravel › array2xml
Laracasts
We cannot provide a description for this page right now
🌐
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.
🌐
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.
🌐
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.
🌐
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, ) ), ) );
🌐
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....
🌐
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 ...
🌐
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
🌐
Laravel.io
laravel.io › forum › 11-03-2015-xml-to-jsonarray-for-storage
XML to JSON/Array for Storage | Laravel.io
Sign in to participate in this thread! ... The Laravel portal for problem solving, knowledge sharing and community building.
Top answer
1 of 3
6

Almost had it! You simply had to pass the $subnode, not $xml into the recursive call of function:

// XML BUILD RECURSIVE FUNCTION
function array_to_xml($array, &$xml) {        
    foreach($array as $key => $value) {               
        if(is_array($value)) {            
            if(!is_numeric($key)){
                $subnode = $xml->addChild($key);
                array_to_xml($value, $subnode);
            } else {
                array_to_xml($value, $subnode);
            }
        } else {
            $xml->addChild($key, $value);
        }
    }        
}

// EXAMPLE ARRAY
$newArray = array(
                 "Project" =>
                  array("ExternalProjectID" => 53,
                        "ProjectName" => "Doon Creek",
                        "Location" => 
                         array ("Address" => "123 Fake Street",
                                "City" => "Toronto",
                                "Province" => "ON",
                                "Latitude" => 43.0000,
                                "Longitude" => -80.0000),
                        "Website" => 
                        "http://www.website.com/our-communities.php?newcommunity=53",
                        "ContactInformation" => 
                         array("ContactPhone" => "555-5555",
                               "ContactEmail" => "[email protected]",
                               "SalesOfficeAddress" => "123 Fake Street",
                               "SalesOfficeCity" => "Toronto",
                               "SalesOfficeProvince" => "ON")
                       )
                );

// CREATING XML OBJECT
$xml = new SimpleXMLElement('<Projects/>'); 
array_to_xml($newArray, $xml);

// TO PRETTY PRINT OUTPUT
$domxml = new DOMDocument('1.0');
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
$domxml->loadXML($xml->asXML());

echo $domxml->saveXML();

Output

<?xml version="1.0"?>
<Projects>
  <Project>
    <ExternalProjectID>53</ExternalProjectID>
    <ProjectName>Doon Creek</ProjectName>
    <Location>
      <Address>123 Fake Street</Address>
      <City>Toronto</City>
      <Province>ON</Province>
      <Latitude>43</Latitude>
      <Longitude>-80</Longitude>
    </Location>
    <Website>http://www.website.com/our-communities.php?newcommunity=53</Website>
    <ContactInformation>
      <ContactPhone>555-5555</ContactPhone>
      <ContactEmail>[email protected]</ContactEmail>
      <SalesOfficeAddress>123 Fake Street</SalesOfficeAddress>
      <SalesOfficeCity>Toronto</SalesOfficeCity>
      <SalesOfficeProvince>ON</SalesOfficeProvince>
    </ContactInformation>
  </Project>
</Projects>
2 of 3
2

In general, it is verified the key is numeric, but the correct one is if the first one is numeric, if there is something empty "_" is added

<?php
$file = 'https://raw.githubusercontent.com/ZiTAL/flickr-php-cli/master/composer.json';
$file = file_get_contents($file);
$array = json_decode($file, true);

$dom = new DOMDocument('1.0', 'utf-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$root = $dom->createElement('root');
$dom->appendChild($root);

array2xml($array, $root, $dom);

echo $dom->saveXML();

function array2xml($array, $node, &$dom)
{
    foreach($array as $key => $value)
    {
        if(preg_match("/^[0-9]/", $key))
            $key = "node-{$key}";
        $key = preg_replace("/[^a-z0-9_\-]+/i", '', $key);

        if($key==='')
            $key = '_';

        $a = $dom->createElement($key);
        $node->appendChild($a);

        if(!is_array($value))
            $a->appendChild($dom->createTextNode($value));
        else
            array2xml($value, $a, $dom);
    }
}

input:

{
    "name": "thefox/flickr-cli",
    "description": "Upload and download Flickr photos, photo sets, directories via shell.",
    "license": "GPL-3.0",
    "type": "project",
    "keywords": [
        "Flickr",
        "Upload",
        "Download",
        "Photo",
        "CLI"
    ],
    "homepage": "https://github.com/TheFox/flickr-cli",
    "authors": [
        {
            "name": "Christian Mayer",
            "email": "[email protected]",
            "homepage": "https://fox21.at"
        }
    ],
    "require": {
        "php": "^7.0",
        "rezzza/flickr": "^1.1",
        "symfony/yaml": "^2.3",
        "symfony/console": "^3.1",
        "symfony/filesystem": "^3.1",
        "symfony/finder": "^3.1",
        "monolog/monolog": "^1.21",
        "guzzlehttp/guzzle": "^3.8",
        "lusitanian/oauth": "^0.2",
        "rych/bytesize": "^1.0",
        "doctrine/dbal": "^2.5"
    },
    "require-dev": {
        "phpstan/phpstan": "^0.7",
        "squizlabs/php_codesniffer": "^3.0"
    },
    "autoload": {
        "psr-4": {
            "": "src"
        }
    },
    "bin": [
        "bin/flickr-cli"
    ]
}

output:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <name>thefox/flickr-cli</name>
  <description>Upload and download Flickr photos, photo sets, directories via shell.</description>
  <license>GPL-3.0</license>
  <type>project</type>
  <keywords>
    <node-0>Flickr</node-0>
    <node-1>Upload</node-1>
    <node-2>Download</node-2>
    <node-3>Photo</node-3>
    <node-4>CLI</node-4>
  </keywords>
  <homepage>https://github.com/TheFox/flickr-cli</homepage>
  <authors>
    <node-0>
      <name>Christian Mayer</name>
      <email>[email protected]</email>
      <homepage>https://fox21.at</homepage>
    </node-0>
  </authors>
  <require>
    <php>^7.0</php>
    <rezzzaflickr>^1.1</rezzzaflickr>
    <symfonyyaml>^2.3</symfonyyaml>
    <symfonyconsole>^3.1</symfonyconsole>
    <symfonyfilesystem>^3.1</symfonyfilesystem>
    <symfonyfinder>^3.1</symfonyfinder>
    <monologmonolog>^1.21</monologmonolog>
    <guzzlehttpguzzle>^3.8</guzzlehttpguzzle>
    <lusitanianoauth>^0.2</lusitanianoauth>
    <rychbytesize>^1.0</rychbytesize>
    <doctrinedbal>^2.5</doctrinedbal>
  </require>
  <require-dev>
    <phpstanphpstan>^0.7</phpstanphpstan>
    <squizlabsphp_codesniffer>^3.0</squizlabsphp_codesniffer>
  </require-dev>
  <autoload>
    <psr-4>
      <_>src</_>
    </psr-4>
  </autoload>
  <bin>
    <node-0>bin/flickr-cli</node-0>
  </bin>
</root>