Last active
August 7, 2021 02:15
-
-
Save WinterSilence/6b1998b252402942fe9a50e5340ef5ab to your computer and use it in GitHub Desktop.
PHP function for convert array to SimpleXMLElement object
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 Enso; | |
| use SimpleXMLElement; | |
| /** | |
| * Converts array to XML object. | |
| * Note: attribute keys must prefix '@'. | |
| * | |
| * @param iterable $data Source data. | |
| * @param string|SimpleXMLElement $parent Parent XML tag. | |
| * @param string $charset Encoding of the XML document. | |
| * @return SimpleXMLElement | |
| */ | |
| function arrayToXml(iterable $data, $parent, string $charset = 'UTF-8'): SimpleXMLElement | |
| { | |
| if (\is_string($parent)) { | |
| $parent = new SimpleXMLElement( | |
| '<?xml version="1.0" encoding="' . $charset . '"?><' . $parent . '/>', | |
| \LIBXML_BIGLINES | \LIBXML_NONET | |
| ); | |
| } | |
| foreach ($data as $name => $value) { | |
| if (\is_object($value) && !$value instanceof \Traversable) { | |
| $value = \method_exists($value, '__toString') ? (string) $value : \get_object_vars($value); | |
| } | |
| if (\is_iterable($value)) { | |
| arrayToXml($value, $parent->addChild($name), $charset); | |
| } elseif (\is_string($name) && $name[0] === '@') { | |
| $parent->addAttribute($name, \htmlspecialchars($value, \ENT_XML1, $charset)); | |
| } else { | |
| $parent->addChild($name, \htmlspecialchars($value, \ENT_XML1, $charset)); | |
| } | |
| } | |
| return $parent; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment