Created
December 13, 2018 11:48
-
-
Save kobus1998/c70e683753c7a1d688bb2b97e671b838 to your computer and use it in GitHub Desktop.
Xml generator
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 | |
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