gal-s
10/30/2019 - 7:05 PM

Array to XML

<?php
header("Content-Type:application/xml");
// Code to convert php array to xml document
//  XML is less good than JSON -  cannot put nameless or numberd arrays keys

// Define a function that converts array to xml.
function arrayToXml($array, $rootElement = null, $xml = null, $preety = true)
{
    $_xml = $xml;

    // If there is no Root Element then insert root
    if ($_xml === null) {
        $_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>');
    }

    // Visit all key value pair
    foreach ($array as $k => $v) {
        // If there is nested array then
        if (is_array($v)) {
            // Call function for nested array
            arrayToXml($v, $k, $_xml->addChild($k));
        } else {
            // Simply add child element.
            $_xml->addChild($k, $v);
        }
    }
    if ($preety) {
        // Pretty XML Output
        $dom = dom_import_simplexml($_xml)->ownerDocument;
        $dom->formatOutput = true;
        return $dom->saveXML();
    } else {
        // Not Pretty XML Output
        return $_xml->asXML();
    }
}

// array 1
$response['userID'] = 57804585;
$response['name'] = 'Gal Sarig';
$response['daughter']['small'] = 'Michal';
$response['daughter']['big'] = 'Zohar';
$response['email'] = 'gal2016@latingate.com';
$response['dateOfBirth'] = '09-05-1967';
$response['colors']['c1'] = 'purple';
$response['colors']['c2'] = 'blue';
$response['colors']['c3'] = 'red';

// array  2
$response2 = array(
    'userID' => 57804585,
    'name' => 'Gal Sarig2',
    'daugther' => array(
        'small' => 'michal',
        'big' => 'zohar'
    ),
    'email' => 'gals@hellmann.co.il',
    'dateOfBirth' => '09-05-1967',
    'colors' => array(
        'c1' => 'purple',
        'c2' => 'blue',
        'ca3' => 'red'
    )
);

echo arrayToXml($response);
//echo arrayToXml($response2);

?>