<?php

class Xml
{
    private $xml;
    private $tab = 0;

    public function __construct($version = '1.0', $encode = 'utf-8')
    {
        $this->xml .= "<?xml version='$version' encoding='$encode'?>\n";
    }

    public function abrirTag($name)
    {
        $this->adicionarTab();
        $this->xml .= "<$name>\n";
        $this->tab++;
    }

    public function fecharTag($name)
    {
        $this->tab--;
        $this->adicionarTab();
        $this->xml .= "</$name>\n";
    }

    public function abrirTagAtributo($name, $attributes = [])
    {
        $this->adicionarTab();
        $this->xml .= "<$name";
        foreach ($attributes as $attr => $value) {
            $this->xml .= " $attr=\"$value\"";
        }
        $this->xml .= ">\n";
        $this->tab++;
    }

    public function adicionarValor($value)
    {
        $this->xml .= "$value\n";
    }

    private function adicionarTab()
    {
        for ($i = 1; $i <= $this->tab; $i++) {
            $this->xml .= "\t";
        }
    }

    public function adicionarTag($name, $value)
    {
        $this->adicionarTab();
        $this->xml .= "<$name>$value</$name>\n";
    }

    public function __toString()
    {
        return $this->xml;
    }

    public function gravarFicheiro($filename)
    {
        file_put_contents($filename, $this->xml);
    }
}
