Convert PHP associative array to XML

Post shows simple PHP function of how to create XML string from associative array. In foreach loop, each item will be closed within XML tag named on key part of array member. After loop is finished, function returns XML string. I also created options to add parent node and write nodes in uppercase.

/**
 * Function returns XML string for input associative array. 
 * @param Array $array Input associative array
 * @param String $wrap Wrapping tag
 * @param Boolean $upper To set tags in uppercase
 */
function array2xml($array, $wrap='ROW0', $upper=true) {
    // set initial value for XML string
    $xml = '';
    // wrap XML with $wrap TAG
    if ($wrap != null) {
        $xml .= "<$wrap>\n";
    }
    // main loop
    foreach ($array as $key=>$value) {
        // set tags in uppercase if needed
        if ($upper == true) {
            $key = strtoupper($key);
        }
        // append to XML string
        $xml .= "<$key>" . htmlspecialchars(trim($value)) . "</$key>";
    }
    // close wrap TAG if needed
    if ($wrap != null) {
        $xml .= "\n</$wrap>\n";
    }
    // return prepared XML string
    return $xml;
}

Here is how to call array2xml function:

// prepare associative array
$arr = Array('color'=>'red', 'size'=>'20px', 'style'=>'bold');
// print XML
print array2xml($arr);

The XML output of above array will finally look like:

<ROW0>
    <COLOR>red</COLOR>
    <SIZE>20px</SIZE>
    <STYLE>bold</STYLE>
</ROW0>

Actually XML will not be so nicely displayed, but it will be well formatted and that’s the most important.

Categories PHP

Leave a Comment