Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class XML
- {
- /**
- * Converts an XML node to an array
- *
- * @param \SimpleXMLElement $node XML node
- *
- * @return array
- *
- * @note Does not handle namespaces
- */
- public static function toArray(\SimpleXMLElement $node)
- {
- $output = array();
- $attributes = array();
- foreach ($node->attributes() as $key => $val) {
- $attributes[$key] = (string)$val;
- }
- $text = trim((string)$node);
- if (! empty($attributes)) {
- $output['@attributes'] = $attributes;
- }
- if (! empty($text)) {
- $output['_'] = $text;
- }
- $children = array();
- foreach ($node->children() as $childName => $childNode) {
- $children[$childName][] = self::toArray($childNode);
- }
- foreach ($children as $childName => $childList) {
- if (count($childList) === 1) {
- $output[$childName] = $childList[0];
- } else {
- $output[$childName] = $childList;
- }
- }
- return $output;
- }
- public static function toObject(\SimpleXMLElement $node)
- {
- $obj = new \stdClass();
- self::toObject_R($obj, self::toArray($node));
- return $obj;
- }
- private static function toObject_R($obj, $item)
- {
- if (! is_array($item)) {
- return;
- }
- foreach ($item as $key => $val) {
- if (is_array($val)) {
- if (array_keys($val) === range(0, count($val) - 1)) {
- $q = array();
- foreach ($val as $i => $v) {
- $q[$i] = new \stdClass();
- self::toObject_R($q[$i], $v);
- }
- $obj->$key = $q;
- } else {
- $obj->$key = new \stdClass();
- self::toObject_R($obj->$key, $val);
- }
- } else {
- $obj->$key = $val;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement