Конверер массива в XML

<?php
class DataConverter {
    static function array2Xml($array, $container = 'values') {
        if(!is_array($array)) {
            throw new Exception('Param must be a array');
        }
        $xml = '';
        foreach($array as $key => $value) {
            if(is_integer($key)) {
                $key = self::getEntityNameFromContainer($container);
            }
            $xml .= (is_array($value)) ? self::array2Xml($value, $key) : self::value2Xml($value, $key);
        }
        return self::value2Xml($xml,$container);
    }

    static function value2Xml($value, $container) {
        return '&lt;'.$container.'>'.$value.'&lt;/'.$container.'>';
    }

    static function getEntityNameFromContainer($containerName, $default = 'entity') {
        if('s' == substr($containerName, -1)) {
            return substr($containerName, 0, strlen($containerName) - 1);
        }
        if(strlen($containerName &lt; 3)) {
            return $default;
        }
        $ending = substr($containerName, -3);
        if('ses' == $ending || 'oes' == $ending || 'xes' == $ending) {
            return substr($containerName, 0, strlen($containerName) - 2);
        }
        if(strlen($containerName &lt; 4)) {
            return $default;
        }
        $ending = substr($containerName, -4);
        if('shes' == $ending || 'ches' == $ending) {
            return substr($containerName, 0, strlen($containerName) - 2);
        }
        return $default;
    }
}

$arr = array(1, 'foos' => array(bar, 2));
echo DataConverter::array2xml($arr, 'childs');

class array2xml {
        protected $xml;

        public function __construct( $elements, $rootnode = 'rootnode' ) {
            $this->xml =new DOMDocument('1.0','iso-8859-1');
            $rootElement=$this->xml->createElement($rootnode,'');
            $this->xml->appendChild($rootElement);
            $this->transform($rootElement, $elements);
        }

        protected function transform($currentNode, $elements) {
            if( is_array($elements)) {
                foreach($elements as $key=>$value) {
                    if(is_array($value)) {
                        $element=$this->xml->createElement($key,'');
                        $currentNode->appendChild($element);
                        $this->transform($element, $value);
                    } else {
                        $element=$this->xml->createElement($key,$value);
                        $currentNode->appendChild($element);
                    }
                }
            } else {
                return false;
            }
        }

        public function xml() {
            return $this->xml->saveXML();
        }
    }
Теги:
Конверер, массив, XML
Добавлено: 19 Апреля 2018 06:16:44 Добавил: Андрей Ковальчук Нравится 0
Добавить
Комментарии:
Нету комментариев для вывода...