note 83881 added to function.xml-parse-into-struct
| From: | jemptymethod at gmail dot com | Date: | Mon, 16 Jun 2008 20:39:30 +0000 |
| Subject: | note 83881 added to function.xml-parse-into-struct | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-140512@lists.php.net to get a copy of this message | ||
@wickedfather, re: beaudurrant....I just cannot concur that the latter's class is
"great"....First of all, it doesn't handle attributes. Second of all, as my code
below demonstrates, there is no need waste processing by determining duplicates within their own
loop. Thirdly, when there are duplicates, it collapses the layer in the array above the duplicates.
Here is some much more consise code, though not (yet) object oriented, and also not yet handling
attributes; it maintains a stack for each level:
<?php
function xml_parse_into_assoc($file) {
$data = implode("", file($file));
$p = xml_parser_create();
xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($p, $data, $vals, $index);
xml_parser_free($p);
$levels = array(null);
foreach ($vals as $val) {
if ($val['type'] == 'open' || $val['type'] ==
'complete') {
if (!array_key_exists($val['level'], $levels)) {
$levels[$val['level']] = array();
}
}
$prevLevel =& $levels[$val['level'] - 1];
$parent = $prevLevel[sizeof($prevLevel)-1];
if ($val['type'] == 'open') {
$val['children'] = array();
array_push(&$levels[$val['level']], $val);
continue;
}
else if ($val['type'] == 'complete') {
$parent['children'][$val['tag']] = $val['value'];
}
else if ($val['type'] == 'close') {
$pop = array_pop($levels[$val['level']]);
$tag = $pop['tag'];
if ($parent) {
if (!array_key_exists($tag, $parent['children'])) {
$parent['children'][$tag] = $pop['children'];
}
else if (is_array($parent['children'][$tag])) {
$parent['children'][$tag][] = $pop['children'];
}
}
else {
return(array($pop['tag'] => $pop['children']));
}
}
$prevLevel[sizeof($prevLevel)-1] = $parent;
}
}
?>
----
Server IP: 209.41.74.194
Probable Submitter: 66.0.112.27
----
Manual Page -- http://www.php.net/manual/en/function.xml-parse-into-struct.php
Edit -- https://master.php.net/note/edit/83881
Del: integrated -- https://master.php.net/note/delete/83881/integrated
Del: useless -- https://master.php.net/note/delete/83881/useless
Del: bad code -- https://master.php.net/note/delete/83881/bad+code
Del: spam -- https://master.php.net/note/delete/83881/spam
Del: non-english -- https://master.php.net/note/delete/83881/non-english
Del: in docs -- https://master.php.net/note/delete/83881/in+docs
Del: other reasons-- https://master.php.net/note/delete/83881
Reject -- https://master.php.net/note/reject/83881
Search -- https://master.php.net/manage/user-notes.php