note 93717 modified in book.dom by thiago

From: Date: Thu, 24 Sep 2009 12:09:40 +0000
Subject: note 93717 modified in book.dom by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-161015@lists.php.net to get a copy of this message
I had problems with the dom2array_full function by "nospam at ya dot ru". Here's my function, which works correctly for my project, and might work for yours: <?php function dom_to_array($root) { $result = array(); if ($root->hasAttributes()) { $attrs = $root->attributes; foreach ($attrs as $i => $attr) $result[$attr->name] = $attr->value; } $children = $root->childNodes; if ($children->length == 1) { $child = $children->item(0); if ($child->nodeType == XML_TEXT_NODE) { $result['_value'] = $child->nodeValue; if (count($result) == 1) return $result['_value']; else return $result; } } $group = array(); for($i = 0; $i < $children->length; $i++) { $child = $children->item($i); if (!isset($result[$child->nodeName])) $result[$child->nodeName] = dom_to_array($child); else { if (!isset($group[$child->nodeName])) { $tmp = $result[$child->nodeName]; $result[$child->nodeName] = array($tmp); $group[$child->nodeName] = 1; } $result[$child->nodeName][] = dom_to_array($child); } } return $result; } ?> --was-- I had problems with the dom2array_full function by "nospam at ya dot ru". Here's my function, which works correctly for my project, and might work for yours: function dom_to_array($root) { $result = array(); if ($root->hasAttributes()) { $attrs = $root->attributes; foreach ($attrs as $i => $attr) $result[$attr->name] = $attr->value; } $children = $root->childNodes; if ($children->length == 1) { $child = $children->item(0); if ($child->nodeType == XML_TEXT_NODE) { $result['_value'] = $child->nodeValue; if (count($result) == 1) return $result['_value']; else return $result; } } $group = array(); for($i = 0; $i < $children->length; $i++) { $child = $children->item($i); if (!isset($result[$child->nodeName])) $result[$child->nodeName] = dom_to_array($child); else { if (!isset($group[$child->nodeName])) { $tmp = $result[$child->nodeName]; $result[$child->nodeName] = array($tmp); $group[$child->nodeName] = 1; } $result[$child->nodeName][] = dom_to_array($child); } } return $result; } http://php.net/manual/en/book.dom.php

« previous php.notes (#161015) next »