Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created December 13, 2018 11:48
Show Gist options
  • Save kobus1998/c70e683753c7a1d688bb2b97e671b838 to your computer and use it in GitHub Desktop.
Save kobus1998/c70e683753c7a1d688bb2b97e671b838 to your computer and use it in GitHub Desktop.
Xml generator
<?php
namespace Util\Xml;
class Generator
{
/**
* @param string $name
* @param string|array $inner (null)
* @param array $attrs (array)
* @param bool $encode (false)
* @return string xml
*/
public function add($name, $inner = null, $attrs = [], $encode = false)
{
$s = "";
$s .= "<$name ";
foreach ($attrs as $key => $value) {
if (is_integer($key)) {
$s .= "$value ";
} else {
$s .= "$key=\"$value\" ";
}
}
$s = trim($s);
if ($inner == null) {
$s .= " />";
return $s;
}
$s .= ">";
if (is_array($inner)) {
$s .= implode($inner);
} else {
$s .= $encode ? htmlspecialchars($inner) :$inner;
}
$s .= "</$name>";
return $s;
}
}
/*
Can be used for html too
$g = new \Util\Xml\Generator();
$g->add("Root", [
$g->add("Address", "123"),
$g->add("City", "abc"),
$g->add("Success")
], ['ID' => 1]);
<Root ID="1">
<Address>123</Address>
<City>abc</City>
<Success />
</Root>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment