<?php
// XML Creator v.2.0.0

class Tag {
	var $name='';
	var $attr=array();
	var $value='';

	function Tag($name='') {
		$name=trim($name);
		if ($this->checkTagName($name)) $this->name=$name;
	}

	function checkTagName($name) {
		if (preg_match('/[^\w\d_-]+/',$name) or !$name) die("<b>Error TagName:</b> \"$name\"");
		else return true;
	}

	function addAttr($name='', $value='') {
		if ($this->checkTagName($name)) $this->attr[$name]=$value;
	}

	function get() {
		$xml='';
		if ($this->name) {
			$xml.="<{$this->name}";
			foreach ($this->attr as $name => $value) $xml.=" {$name}=\"{$value}\"";
			$xml.=">{$this->value}</{$this->name}>";
		}
		return $xml;
	}
}

class XMLCreator {
	var $xml='';
	var $tagList=array();
	var $currentTag=0;

	function XMLCreator($isHeader=true) {
		if ($isHeader) $this->xml='<?xml version="1.0" encoding="UTF-8"?>';
	}

	function openTag($name='') {
		if (isset($this->tagList[$this->currentTag])) $this->currentTag++;
		$this->tagList[$this->currentTag]=new Tag($name);
	}

	function setValue($value='', $addType=false) {
		if (isset($this->tagList[$this->currentTag])) {
			$this->tagList[$this->currentTag]->value=($addType ? $this->tagList[$this->currentTag]->value : '').$value;
		} else $this->xml=($addType ? $this->xml : '').$value;
	}

	function addAttr($name, $value='') {
		if (isset($this->tagList[$this->currentTag])) $this->tagList[$this->currentTag]->addAttr($name, $value);
	}
	
	function closeTag() {
		if (isset($this->tagList[$this->currentTag])) {
			$xml=$this->tagList[$this->currentTag]->get();
			$this->tagList[$this->currentTag]=NULL;
			$this->currentTag--;
			$this->setValue($xml, true);
		}
	}

	function closeAll() {
		while(isset($this->tagList[$this->currentTag])) $this->closeTag();
	}

	function addTag($name, $value='', $attr=array()) {
		$this->openTag($name);
		foreach ($attr as $attrName => $attrValue) $this->addAttr($attrName, $attrValue);
		$this->setValue($value);
		$this->closeTag($name);
	}

	function addXML($xml='') {
		if (isset($this->tagList[$this->currentTag])) $this->tagList[$this->currentTag]->value=$xml;
		else $this->xml.=$xml;
	}


	function get() {
		$this->closeAll();
		return $this->xml;
	}

	function length() {
		return strlen($this->xml);
	}

	function output() {
		header('Content-type: text/xml');
		//header('Content-Length: '.$this->length());
		print $this->get();
	}
}
?>