Last active
August 29, 2015 14:09
-
-
Save vladkens/2af2f262a59c19648e7d to your computer and use it in GitHub Desktop.
XML represents as array
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 | |
| define('XML_RETURN_DOM_ELEMENT', 1); | |
| define('XML_WITHOUT_DECLARATION', 2); | |
| define('XML_PRETTY_PRINT', 4); | |
| function xml_decode($node) { | |
| $node = is_string($node) ? new \SimpleXMLElement($node) : $node; | |
| $result = ['tag' => $node->getName()]; | |
| foreach ($node->attributes() as $name => $value) { | |
| $value = (array) $value; | |
| $result['@' . $name] = $value[0]; | |
| } | |
| $result['children'] = []; | |
| foreach ($node->children() as $name => $child) { | |
| $result['children'][] = xml_decode($child); | |
| } | |
| return $result; | |
| } | |
| function xml_encode($node, $param = 0) { | |
| $node = array_merge(['tag' => 'root', 'children' => []], $node); | |
| $document = new \DOMDocument(); | |
| $result = $document->createElement($node['tag']); | |
| foreach ($node as $name => $value) { | |
| if (substr($name, 0, 1) != '@') continue; | |
| $result->setAttribute(substr($name, 1), $value); | |
| } | |
| foreach ($node['children'] as $child) { | |
| $child = xml_encode($child, XML_RETURN_DOM_ELEMENT); | |
| $result->appendChild($document->importNode($child, true)); | |
| } | |
| if ($param & XML_RETURN_DOM_ELEMENT) { | |
| return $result; | |
| } | |
| $document->appendChild($result); | |
| if ($param & XML_PRETTY_PRINT) { | |
| $document->formatOutput = true; | |
| } | |
| $result = $document->saveXML(); | |
| if ($param & XML_WITHOUT_DECLARATION) { | |
| $result = str_replace("<?xml version=\"1.0\"?>\n", '', $result); | |
| } | |
| return $result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment