PHP – Array to XML Conversion

The following function presents a simple approach to convert PHP arrays to their XML counterpart. It supports nested arrays too. Internally, it uses SimpleXMLElement to do the actual work.

/**
 * @param array $array the array to be converted
 * @param string? $rootElement if specified will be taken as root element, otherwise defaults to 
 *                <root>
 * @param SimpleXMLElement? if specified content will be appended, used for recursion
 * @return string XML version of $array
 */
function arrayToXml($array, $rootElement = null, $xml = null) {
  $_xml = $xml;

  if ($_xml === null) {
    $_xml = new SimpleXMLElement($rootElement !== null ? $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();
}

Examples are:

echo arrayToXml(array('testOne' => 'xml'));
echo arrayToXml(array('testOne' => array('testOneInner' => 'content')));
echo arrayToXml(array('testOne' => array('testOneInner' => 'content'), 'testTwo' => 'content'));
echo arrayToXml(array('testOne' => array('testOneInner' => array('testOneInnerInner' => 'content')), 'testTwo' => 'content'));
echo arrayToXml(array('testOne' => array('testOneInner' => array('testOneInnerInner' => 'content')), 'testTwo' => array('testTwoInner' => array('testTwoInnerInner' => 'content'))));

which produces:

<?xml version="1.0"?>
<root><testOne>xml</testOne></root>
<?xml version="1.0"?>
<root><testOne><testOneInner>content</testOneInner></testOne></root>
<?xml version="1.0"?>
<root><testOne><testOneInner>content</testOneInner></testOne><testTwo>content</testTwo></root>
<?xml version="1.0"?>
<root><testOne><testOneInner><testOneInnerInner>content</testOneInnerInner></testOneInner></testOne><testTwo>content</testTwo></root>
<?xml version="1.0"?>
<root><testOne><testOneInner><testOneInnerInner>content</testOneInnerInner></testOneInner></testOne><testTwo><testTwoInner><testTwoInnerInner>content</testTwoInnerInner></testTwoInner></testTwo></root>

You may also like...

3 Responses

  1. shegun babs says:

    hello Matthias,
    wanted to ask, how can I remove the starting tag ”
    I wont be needing this.
    Thanks.

  2. Sravan says:

    NIce Post I have Working well Thanks.

  3. Jaydeep says:

    Works perfectly .Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.