Skip to content

Instantly share code, notes, and snippets.

@gustavo-rodrigues-dev
Last active August 29, 2015 14:02
Show Gist options
  • Save gustavo-rodrigues-dev/0966bfa7159181df6bc2 to your computer and use it in GitHub Desktop.
Save gustavo-rodrigues-dev/0966bfa7159181df6bc2 to your computer and use it in GitHub Desktop.
Montar XML com base em arrays multidimensionais, mantendo sua estrutura
<?php
class MakeDomXml{
public $dom;
public $output ;
function __construct(){
$options = func_get_args();
$this->dom = new DOMDocument('1.0', 'UTF-8');
$this->dom->formatOutput = true;
$this->dom->preserveWhiteSpace = false;
if(is_array($options[0])){
$this->output = $this->setElement($options[0]);
}
}
public function __toString() {
foreach ($this->output as $value) {
$this->dom->appendChild($value);
}
return $this->dom->saveXML();
}
public function setElement(Array $arg){
$return = array();
foreach ($arg as $key => $value) {
if($value != ''){
if(is_array($value)){
$elemts = $this->setElement($value);
$father = $this->dom->createElement($key);
if(is_array($elemts)){
foreach ($elemts as $element) {
$father->appendChild($element) ;
}
}
$return[] = $father;
} else {
$return[] = $this->dom->createElement($key, $value);
}
} else {
$return[] = $this->dom->createElement($key);
}
}
return $return;
}
public function make(Array $arg){
$this->output = $this->setElement($arg);
}
}
$teste = array('smart' => array('usuario' => array('id' => 10)), 'teste' => 'aaaa');
$monta = new MakeDomXml($teste);
echo $monta;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment