00001 <?php
00013 class XML{
00014 private $xml;
00015 private $encoding = 'UTF-8';
00016
00020 public function __construct($objeto){
00021 $this->xml = new DomDocument('1.0', $this->encoding);
00022 $nodoRaiz = $this->crearXML($objeto, get_class($objeto));
00023 $this->xml->appendChild($nodoRaiz);
00024 }
00025 private function crearXML($objeto, $nombreElemento='respuesta'){
00026
00027
00028 if(!$nombreElemento) $nombreElemento = 'respuesta';
00029 if(is_object($objeto)){
00030 $nombreElemento = get_class($objeto);
00031 $elemento = $this->xml->createElement($nombreElemento);
00032 if (method_exists($objeto, "verAtributos"))
00033 $vars = $objeto->verAtributos();
00034 else
00035 $vars = get_object_vars($objeto);
00036 }
00037
00038 if(is_array($objeto)){
00039 $elemento = $this->xml->createElement($nombreElemento);
00040 $vars = $objeto;
00041 }
00042
00043 if(is_scalar($objeto)){
00044
00045 $elemento = $this->xml->createElement($nombreElemento);
00046 $nodo = $this->xml->createTextNode($objeto);
00047 $elemento->appendChild($nodo);
00048 return $elemento;
00049 }
00050
00051 foreach($vars as $atributo => $valor){
00052 if(is_scalar($valor) OR ($valor == '')){
00053
00054 if (is_numeric($atributo))
00055 $elemento->appendChild($this->crearXML($valor,'item'));
00056 else
00057
00058 $elemento->setAttribute($atributo, $valor);
00059 }elseif(is_array($valor)){
00060 if (is_numeric($atributo)) $atributo="item";
00061 $elemento->appendChild($this->crearXML($valor, $atributo));
00062 }elseif(is_object($valor)) {
00063 $elemento->appendChild($this->crearXML($valor, get_class($valor)));
00064 }else throw new ExcepcionXMLAtributoDesconocido($atributo);
00065 }
00066
00067 return $elemento;
00068 }
00071 public function verXML(){
00072 $this->xml->encoding = $this->encoding;
00073 return $this->xml->saveXML();
00074 }
00075 }
00076
00077 class ExcepcionXMLAtributoDesconocido extends Excepcion{
00079 public function __construct($atributo){
00080 $titulo = "No se pudo construir el atributo de un objeto XML";
00081 $texto = "La aplicación intentó crear un objeto XML, pero el atributo ($atributo) del objeto php es de un tipo desconocido.";
00082 $solucion = "Debe tratarse de un error de programación.";
00083 parent::__construct($titulo,$texto,$solucion);
00084 }
00085 }
00086
00087
00088 return true;
00089 ?>