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 )