a::xml PHP Method

xml() static public method

Converts an array to a XML string
static public xml ( array $array, string $tag = 'root', boolean $head = true, string $charset = 'utf-8', $tab = ' ', integer $level ) : string
$array array The source array
$tag string The name of the root element
$head boolean Include the xml declaration head or not
$charset string The charset, which should be used for the header
$level integer The indendation level
return string The XML string
    static function xml($array, $tag = 'root', $head = true, $charset = 'utf-8', $tab = '  ', $level = 0)
    {
        $result = $level == 0 && $head ? '<?xml version="1.0" encoding="' . $charset . '"?>' . "\n" : '';
        $nlevel = $level + 1;
        $result .= str_repeat($tab, $level) . '<' . $tag . '>' . "\n";
        foreach ($array as $key => $value) {
            $key = str::lower($key);
            if (is_array($value)) {
                $mtags = false;
                foreach ($value as $key2 => $value2) {
                    if (is_array($value2)) {
                        $result .= self::xml($value2, $key, $head, $charset, $tab, $nlevel);
                    } else {
                        if (trim($value2) != '') {
                            $value2 = htmlspecialchars($value2) != $value2 ? '<![CDATA[' . $value2 . ']]>' : $value2;
                            $result .= str_repeat($tab, $nlevel) . '<' . $key . '>' . $value2 . '</' . $key . '>' . "\n";
                        }
                    }
                    $mtags = true;
                }
                if (!$mtags && count($value) > 0) {
                    $result .= self::xml($value, $key, $head, $charset, $tab, $nlevel);
                }
            } else {
                if (trim($value) != '') {
                    $value = htmlspecialchars($value) != $value ? '<![CDATA[' . $value . ']]>' : $value;
                    $result .= str_repeat($tab, $nlevel) . '<' . $key . '>' . $value . '</' . $key . '>' . "\n";
                }
            }
        }
        return $result . str_repeat($tab, $level) . '</' . $tag . '>' . "\n";
    }

Usage Example

Example #1
0
    function testArrayXML()
    {
        $this->assertEqual(a::xml($this->arr), '<?xml version="1.0" encoding="utf-8"?>
<root>
  <cat>miao</cat>
  <dog>wuff</dog>
  <bird>tweet</bird>
</root>
');
    }