Last Updated: February 25, 2016
·
712
· webfacer

XML-Object encoding

This i use for encoding Array- or a JSON-Object into XML.
The param $obj stands for the given object in that case it´s an Array or a JSON.
The second param it´s the $level which is used for for getting the depth of the element in XML which is used recursive to get also the associative objects.

function XMLEncode($obj, $level = 1, $xml = NULL)
{
    if(!$obj){
        return FALSE;
    }

    if($level==1) 
    {
        $xml .= '<?xml version="1.0" encoding="ISO-8859-1"?>'."\n"; 
    }

    if(is_array($obj) || is_object($obj)) {

        foreach ($obj as $key => $value)
        {
            $key = strtolower($key);

            if($level>1)
            {
                $node = $xml;
            }

            $xml .= sprintf(str_repeat("\t", $level).'<%s>', $key);

            if (is_array($value) || is_object($value))
            {
                $xml .= XMLEncode($value, $level+1);
            }
            else
            {
                if (trim($value) != NULL)
                {
                    if (htmlspecialchars($value) != $value) 
                    {
                        $xml .= str_repeat("\t",$level)."<![CDATA[$value]]>\n";
                    } 
                    else 
                    {
                        $xml .= str_repeat("\t",$level)."$value\n";
                    }
                }
            }

            $xml .= sprintf(str_repeat("\t",$level).'</%s>', $key);
        }

        return $xml;

    }
    else
    {
        return (string)$obj;
    }

    return $obj;
}