note 59753 deleted from function.xml-parse-into-struct by cmb
| From: | cmb@php.net | Date: | Sun, 06 Oct 2019 08:27:51 +0000 |
| Subject: | note 59753 deleted from function.xml-parse-into-struct by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212524@lists.php.net to get a copy of this message | ||
Note Submitter: VampBoy
----
WHUPS! that was a broken test version.here is the real one:
class xml2array{
/* This class parses XML tags into a recursive, associative array with the tags as the associative
array elements names.
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);
$semicomplete = $this->subdivide($arraydat);
$complete = $this->correctentries($semicomplete);
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));
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;
}
function correctentries($dataarray){
if (is_array($dataarray)){
$keys = array_keys($dataarray);
if (count($keys)== 1 && is_int($keys[0])){
$tmp = $dataarray[0];
unset($dataarray[0]);
$dataarray = $tmp;
}
$keys2 = array_keys($dataarray);
foreach($keys2 as $key){
$tmp2 = $dataarray[$key];
unset($dataarray[$key]);
$dataarray[$key] = $this->correctentries($tmp2);
unset($tmp2);
}
}
return $dataarray;
}
}