note 59751 deleted from function.xml-parse-into-struct by dmytton

From: Date: Thu, 15 Dec 2005 07:35:04 +0000
Subject: note 59751 deleted from function.xml-parse-into-struct by dmytton
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-100176@lists.php.net to get a copy of this message
Note Submitter: VampBoy ---- For the sake of offering a completely different approach to the problem of parsing into a nested array, here is teh solution I came up with. Works pretty well, and reasonably fast, though maybe a little memory intensive: class xml2array{ /* This class parses XML tags into a recursive, associative array with the tags as the associative array elements names. Function names are descriptive; if it encounters multiples of the same tag within a stream, it enumerates them as a sub array under the tag thus: Array ( [Lvl1tag] => Array ( [0] => Array( [Lvl2tag] = "foo") [1]=> Array( [Lvl2tag] = "bar") ) ) It tries to detect when there is only one copy of a tag under another, and concatinate properly. */ function readxmlfile($xmlfile){ // reads XML file in and returns it $xmlstream =fopen($xmlfile,r); $xmlraw=fread($xmlstream,1000000); fclose($xmlstream); return $xmlraw; } function parseXMLintoarray ($xmldata){ // starts the process and returns the final array $xmlparser = xml_parser_create(); xml_parse_into_struct($xmlparser, $xmldata, $arraydat); xml_parser_free($xmlparser); $complete = $this->subdivide($arraydat); return $complete; } function subdivide ($dataarray, $level = 1){ foreach ($dataarray as $key => $dat){ if ($dat[level] === $level && $dat[type] === "open"){ $toplvltag = $dat[tag]; } elseif ($dat[level] === $level && $dat[type] === "close" && $dat[tag]=== $toplvltag){ $newarray[$toplvltag][] = $this->subdivide($temparray,($level +1)); $keys = array_keys($newarray[$toplvltag]); if (count($keys)== 1 && is_int($keys[0])){ $tmp = $newarray[$toplvltag][0]; unset($newarray[$toplvltag][0]); $newarray[$toplvltag] = $tmp; } unset($temparray,$nextlvl); } elseif ($dat[level] === $level && $dat[type] === "complete"){ $newarray[$dat[tag]]=$dat[value]; } elseif ($dat[type] === "complete"||$dat[type] === "close"||$dat[type] === "open"){ $temparray[]=$dat; } } return $newarray; } }

« previous php.notes (#100176) next »