PHP - Convert XML to Object

2

Is there a way with PHP to transpose an XML into an object and object in xml? Example:

** Classe (objeto) **

<?php
class Telefone {
  private $codigoArea;
  private $numero;

  public function setCodigoArea($codigoArea) {
      $this->codigoArea = $codigoArea;
  }

  public function getCodigoArea(){
      return $this->codigoArea;
  }

  public function setNumero($numero) {
      $this->numero = $numero;
  }

  public function getNumero(){
      return $this->numero;
  }
}
?>

** XML **

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<telefone>
   <codigoArea></codigoArea>
   <numero></numero>
</telefone>


** Exemplo do que preciso: **

$fone = new Telefone();
$xml = algumMetodoFuncao($fone); --> Algum metodo/função que transforme meu objeto em XML (O $fone não é uma string)
    
asked by anonymous 03.08.2018 / 16:36

2 answers

1

I created a static class called XMLobject to do this. It has 2 functions:

  • GenerateXML () : Get an object and create a file in the selected directory
  • generateObject () : It receives an xml file and generates the object with the parameters inside the file

For these functions to work, some rules have to be followed.

GenerateXML ()

The entire xml element can only be generated if there is a public getter of the attribute. This means that if you want to generate a <nome> element in xml, getNome() .

generateObject ()

The class of the object that will be created must be included before calling this method. Otherwise it will generate an error. Also, the entire xml element needs a setter in the class. This means that if you have a <sobrenome> element in the xml you need a setSobrenome() in the class.

XMLobject class

class XMLobject {

    static function gerarXML($objeto, $dir =""){

        $class = get_class ($objeto);
        $methods = get_class_methods ($class);
        $atributos = [];
        $functions = [];

        // recupera os atributos através dos metodos
        foreach($methods as $key => $method){
            if(strpos($method, "get") !== false && strpos($method, "get") === 0){
                $atributos[] = lcfirst(substr($method,3,strlen($method) -1));
                $functions[] = $method;
            }
        }

        // cria o xml com os valores dos geters
        $stringXML  = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
        $stringXML .= '<'.$class.'>';
        for($i = 0; $i < count($atributos); $i++){
            $function = $functions[$i];
            $stringXML .= '<'.$atributos[$i].'>'.$objeto->$function().'</'.$atributos[$i].'>';
        }
        $stringXML .= '</'.$class.'>';

        // gera o arquivo no diretorio informado
        file_put_contents($dir.$class.".xml",$stringXML);
    }

    static function gerarObjeto($xml_uri){
        // pega todos os elementos do arquivo xml
        $content = file_get_contents($xml_uri);
        preg_match_all('/<[\w\s\d\"\'\.]+[^\/]>[\w\d]*/', $content, $elementos);
        $obj = null;
        foreach($elementos[0] as $key => $elemento){    
            $valores = explode(">", $elemento);
            $atributo = substr($valores[0],1, strlen($valores[0]));
            if($key == 0) {
                // gera a classe
                $obj = new $atributo();
                continue;
            }
            if(is_object($obj)){
                // insere os valores nos atributos do objeto
                $method = "set".ucfirst($atributo);
                $obj-> $method($valores[1]);
            }
        }
        return $obj;
    }

}

Example Usage:

Generating an xml

$telefone = new Telefone();
$telefone -> setNumero("9999999999");
$telefone -> setCodigoArea("11");
XMLobject::gerarXML($telefone);

Result: (file: Phone.xml)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Telefone>
        <codigoArea>11</codigoArea>
        <numero>9999999999</numero>
    </Telefone>

Generating an Object

$obj = XMLobject::gerarObjeto("Telefone.xml");
print_r($obj);

Result:

Telefone Object ( [codigoArea:Telefone:private] => 11
[numero:Telefone:private] => 9999999999 )
    
03.08.2018 / 20:53
1
$xml = simplexml_load_string($string);
    
03.08.2018 / 16:43