<?php

class SimpleXMLElement {
  
  var $root;
  
  function SimpleXMLElement($data) {
    $data = trim($data);
    $pos = strpos($data, '><');
    $header = substr($data, 0, $pos + 1);
    $pos = strpos($header, ' ');
    if ($pos !== false) {
      $attribute = trim(substr($header, $pos));
      $header = substr($header, 1, $pos);
      $this->root =& new xmlNode($header);
      $tmp = explode('=', $attribute);
      $this->root->addAttribute(trim($tmp[0]), substr($tmp[1], 1, strlen($tmp[1]) - 3));
    } else {
      $header = str_replace(array('<', '>'), '', $header);
      $this->root =& new xmlNode($header);
    }
    return $this->root;
  }
  
  function &addChild($name, $value = '') {
    $child =& new xmlNode($name, $value);
    $this->root->child[] =& $child;
	return $child;
  }
  
  function asXML() {
    return '<?xml version="1.0"?>' . "\n" . $this->root->output();
  }
}

class xmlNode {
  var $attributes, $value, $name, $child;
  
  function &xmlNode($data, $value = '') {
    $this->name = trim($data);
    $this->value =& $value;
    $this->child = array();
    $this->attributes = '';
  }
  
  function &addChild($name, $value = '') {
    $child =& new xmlNode($name, $value);
    $this->child[] =& $child;
	return $child;
  }
  
  function addAttribute($name, $value) {
	$data = $this->attributes . ' ' . $name . '=' . '"' . $value . '"';
    $this->attributes =& $data;
  }
  
  function output($indent = '') {
    $data = $indent . '<' . $this->name;
    if ($this->attributes != '') {
      $data .= $this->attributes;
    }
    $data .= '>';
    if ($this->value != '') {
	  $data .= $this->value . '</' . $this->name . '>' . "\n";
    } else {
	  if (sizeof($this->child) > 0) {
	    $data .= "\n";
        foreach ($this->child as $value) {
          $data .= $value->output($indent . '  ');
        }
        $data .= $indent . '</' . $this->name . '>' . "\n";
	  } else {
        $data .= '</' . $this->name . '>' . "\n";
	  }
    }
    return $data;
  }
}

?>