Posted on 4 Comments

PHP – Array to XML Conversion

PHP Logo

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"?>
<?xml version="1.0"?>
<?xml version="1.0"?>
<?xml version="1.0"?>
<?xml version="1.0"?>

4 thoughts on “PHP – Array to XML Conversion

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

  2. NIce Post I have Working well Thanks.

  3. Works perfectly .Thanks.

  4. how to get tag name in pascal case (Camel Case)

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.