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 )
My answer was correct?
– Andrei Coelho
Right... That’s right... Thank you
– Mamga