<?php

class XMLTag
{
  var $Name;
  var $Attributes;
  var $SubElements;
  var $EndSymbol;
  var $ShringEmpty;

  function __construct($Name = '')
  {
    $this->Name = $Name;
    $this->Attributes = array();
    $this->SubElements = array();
    $this->EndSymbol = '/';
    $this->ShringEmpty = true;
  }

  function GetOutput()
  {
    $Content = '';
    if(is_array($this->SubElements))
    foreach($this->SubElements as $SubElement)
    {
      if(is_object($SubElement)) $Content .= $SubElement->GetOutput();
        else $Content .= $SubElement;
    } else $Content .= $this->SubElements;

    $AttributesText = '';
    foreach($this->Attributes as $Name => $Value)
      $AttributesText .= ' '.$Name.'="'.$Value.'"';

    if($this->Name != '')
    {
      if(($Content != '') or ($this->ShringEmpty == false)) $Output = '<'.$this->Name.$AttributesText.'>'.$Content.'<'.$this->EndSymbol.$this->Name.'>';
        else $Output = '<'.$this->Name.$AttributesText.$this->EndSymbol.'>';
    } else $Output = $Content;
    return($Output);
  }
}

class XMLDocument
{
  var $Formated;
  var $Version;
  var $Encoding;
  var $Content;
  var $Indentation;
  
  function __construct()
  {
    $this->Version = '1.0';
    $this->Encoding = 'utf-8';
    $this->Formated = false;
    $this->Indentation = 2;
  }
  
  function GetOutput()
  {
    $BaseTag = new XMLTag('?xml');
    $BaseTag->Attributes = array('version' => $this->Version, 'encoding' => $this->Encoding);
    $BaseTag->EndSymbol = '?';
    $Output = $BaseTag->GetOutput();
    $Output .= $this->Content->GetOutput();
    if($this->Formated) $Output = $this->FormatOutput($Output);
    return($Output);
  }

  function FormatOutput($Text)
  {
    $Output = '';
    $Indent = 0;
    $IndentNew = 0;
    while($Text != '')
    {
      $Start = strpos($Text, '<');
      $End = strpos($Text, '>');
      if($Start != 0)
      {
        $End = $Start - 1;
        $Start = 0;
      }
      $Line = trim(substr($Text, $Start, $End + 1));
      if(strlen($Line) > 0)
      if($Line[0] == '<')
      {
        if($Text[$Start + 1] == '/')
        {
          $IndentNew = $IndentNew - $this->Indentation;
          $Indent = $IndentNew;
        } else
        {
          if(strpos($Line, ' ')) $Command = substr($Line, 1, strpos($Line, ' ') - 1);
          else $Command = substr($Line, 1, strlen($Line) - $this->Indentation);
          if(strpos($Text, '</'.$Command.'>')) $IndentNew = $IndentNew + $this->Indentation;
        }
      }
      if($Line != '') $Output .= (str_repeat(' ', $Indent).$Line."\n");
      $Text = substr($Text, $End + 1, strlen($Text));
      $Indent = $IndentNew;
    }
    return($Output);
  }
}

?>
