Created
February 15, 2023 13:22
-
-
Save diloabininyeri/4203eef573541a56b4f694498e9a4c26 to your computer and use it in GitHub Desktop.
The an advance xml builder class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
the output