Skip to content

Instantly share code, notes, and snippets.

@diloabininyeri
Created February 15, 2023 13:22
Show Gist options
  • Save diloabininyeri/4203eef573541a56b4f694498e9a4c26 to your computer and use it in GitHub Desktop.
Save diloabininyeri/4203eef573541a56b4f694498e9a4c26 to your computer and use it in GitHub Desktop.
The an advance xml builder class
<?php
class Xmlbuilder
{
private SimpleXMLElement $element;
public function __construct(SimpleXMLElement $simpleXMLElement = new SimpleXMLElement('<root/>'))
{
$this->element = $simpleXMLElement;
}
public function add(string $key, string $value): self
{
$this->element->addChild($key, $value);
return $this;
}
public function addNested(string $key, array $values): self
{
$parentElement = $this->element->addChild($key);
foreach ($values as $keyName => $value) {
if (is_array($value)) {
$this->addNested($keyName, $value);
continue;
}
$parentElement?->addChild($keyName, $value);
}
return $this;
}
public function __toString(): string
{
return $this->element->asXML();
}
public function child(string $parentElement, Closure $closure): self
{
$closure(new self($this->element->addChild($parentElement)));
return $this;
}
}
$fluid = new Xmlbuilder();
$fluid
->add('a', '1')
->add('b', '2')
->add('c', '3')
->addNested('nested', ['foo' => 'bar'])
->child('detail', function (Xmlbuilder $fluid) {
$fluid
->add('city', 'madrid')
->child('region', function (Xmlbuilder $fluid) {
$fluid->add('country', 'spain');
});
})
->add('e', 5);
echo $fluid;
@diloabininyeri
Copy link
Author

diloabininyeri commented Feb 15, 2023

the output

<?xml version="1.0"?>
<root>
    <a>1</a>
    <b>2</b>
    <c>3</c>
    <nested>
        <foo>bar</foo>
    </nested>
    <detail>
        <city>madrid</city>
        <region>
            <country>spain</country>
        </region>
    </detail>
    <e>5</e>
</root>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment