Tag: nested

  • PHP – Array to XML Conversion

    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>