PHP - Convert XML to Object

Asked

Viewed 451 times

2

Is there a way with PHP to transfer an XML in 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)
  • My answer was correct?

  • 1

    Right... That’s right... Thank you

2 answers

1

$xml = simplexml_load_string($string);
  • I don’t have an XML/String... in this case how would it look $xml = simplexml_load_string( ?? ); ? Thank you

  • in the PHP manual you have an example. http://php.net/manual/en/function.simplexml-load-string.php

  • Yes the simplexml-load-string I had seen, but as I understood it does not meet what I need... I made a correction to my question. Now I have an example of what I need. Thank you

1


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

  • gerarXML() : Receives an object and creates a file in the selected directory
  • gerarObject() : Takes an xml file and generates the object with the parameters inside the file

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

gerarXML()

Any xml element can only be generated if there is a public getter of the attribute. This means that if you want to generate an element <nome> in xml, the class of your object should contain a getNome().

gerarObject()

The class of the object to be created must be included before calling this method. Otherwise it will generate an error. In addition, every xml element needs a Setter in the class. This means that if you have an element <sobrenome> in xml a setSobrenome() in 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 of Use:

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);

Upshot:

Telefone Object ( [codigoArea:Telefone:private] => 11
[numero:Telefone:private] => 9999999999 )
  • Perfect... that’s just what I need... Thank you very much

  • @Mamga how good it worked. = ) any doubt can call me!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.