<?php

namespace apexl\Utils\Xml;

class Convert
{
    public static function processXml(string $xml, $return = 'array', $stripBackslashes = true)
    {
        if ($stripBackslashes) {
            $xml = str_replace('\\', "", $xml);
        }
        //check for encoding, we know the first few chars of valid XML for simplexml_load_string:
        if (str_starts_with($xml, "%3C%3Fxml")) {
            $xml = urldecode($xml);
        }
        //Strip the '§' character as this is not valid for XML.
        if (str_contains($xml, '§')) {
            $xml = str_replace('§', ' ', $xml);
        }
        if ($return == 'array') {
            return self::xml2array(simplexml_load_string($xml));
        }

        return simplexml_load_string($xml);
    }

    /**
     * Convert simpleXML object to array.
     * @see http://www.php.net/manual/en/ref.simplexml.php#111227
     * @param string $xml
     * @return array
     */
    public static function xml2array($xmlObject)
    {
        foreach ((array)$xmlObject as $index => $node) {
            $out[$index] = (is_object($node) || is_array($node)) ? self::xml2array($node) : $node;
        }

        return $out;
    }
}
