Skip to content

Instantly share code, notes, and snippets.

@vaneves
Created April 10, 2016 02:15
Show Gist options
  • Save vaneves/1ac7cb07084e956d581a15b979d8fffc to your computer and use it in GitHub Desktop.
Save vaneves/1ac7cb07084e956d581a15b979d8fffc to your computer and use it in GitHub Desktop.
Classe para gerar XML
<?php
class XMLElement
{
private $tag = null;
private $value = null;
private $childs = [];
private $attributes = [];
private $isRoot = true;
private $isCDATA = false;
public function __construct($tag)
{
$this->tag = $tag;
}
public function addAttribute($name, $value = null)
{
$this->attributes[$name] = $value;
}
public function addChild($name, $value = null)
{
$child = new XMLElement($name, $value);
$child ->isRoot = false;
$child ->value = $value;
$this->childs[] = $child;
return $child;
}
public function addChildCDATA($name, $value = null)
{
$child = $this->addChild($name, $value);
$child->isCDATA = true;
return $child;
}
public function asXML()
{
$xml = $this->isRoot ? '<?xml version="1.0" encoding="iso-8859-1"?>' . NL : '';
if(count($this->childs)) {
$xml .= '<' . $this->tag . $this->getAttributes() . '>' . NL;
foreach ($this->childs as $child) {
$xml .= "\t" . $child->asXML();
}
$xml .= "\t" . '</' . $this->tag . '>' . NL;
} else if($this->value) {
$xml .= "\t" . '<' . $this->tag . $this->getAttributes() . '>';
$xml .= $this->isCDATA ? '<![CDATA['. $this->value . ']]>' : htmlentities($this->value);
$xml .= '</' . $this->tag . '>' . NL;
} else {
$xml .= "\t" . '<' . $this->tag . $this->getAttributes() . '/>' . NL;
}
return $xml;
}
private function getAttributes()
{
$attributes = [];
foreach ($this->attributes as $key => $value) {
$attributes[] = $value ? $key . '="' . $value . '"' : $key;
}
return (count($attributes) ? ' ' : '') . implode(' ', $attributes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment