note 81342 deleted from ref.simplexml by danbrown

From: Date: Mon, 18 May 2009 01:14:28 +0000
Subject: note 81342 deleted from ref.simplexml by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155499@lists.php.net to get a copy of this message
Note Submitter: maxim [at] novozhilov dot kiev dot ua ---- One more comment to Jason's XMLToArray function. The best and right way, which I found for multidimensional arrays and tags with the same names is this hook(see method convert). This will right save all data in right array without losing first element of same_nodes_name (this happens when we find first element, saves it and when find later one more with the same_nodes_name, we need to recreate array to save old data in [0] element of new array, otherwise our first element will be outside of array /see my previous post/). Also I made this little class for facility. final class XMLToArray { public function parse($xml) { return $this->convert(simplexml_load_string($xml)); } function convert($xml) { if ($xml instanceof SimpleXMLElement) { $children = $xml->children(); $return = null; } foreach ($children as $element => $value) { if ($value instanceof SimpleXMLElement) { $values = (array)$value->children(); if (count($values) > 0) { if (is_array($return[$element])) { //hook foreach ($return[$element] as $k=>$v) { if (!is_int($k)) { $return[$element][0][$k] = $v; unset($return[$element][$k]); } } $return[$element][] = $this->convert($value); } else { $return[$element] = $this->convert($value); } } else { if (!isset($return[$element])) { $return[$element] = (string)$value; } else { if (!is_array($return[$element])) { $return[$element] = array($return[$element], (string)$value); } else { $return[$element][] = (string)$value; } } } } } if (is_array($return)) { return $return; } else { return false; } } }

« previous php.notes (#155499) next »