note 63879 deleted from function.xml-parse-into-struct by cmb
| From: | cmb@php.net | Date: | Sun, 06 Oct 2019 08:27:54 +0000 |
| Subject: | note 63879 deleted from function.xml-parse-into-struct by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212525@lists.php.net to get a copy of this message | ||
Note Submitter: matt at australiangamer dot com
----
I liked VampBoy's code as it gave me structure pretty much as I wanted it. Just two notes,
though:
There is a bug in this code. subdivide() checks for pre-existing values, but not in the case of a
"complete" element.
In the following (appallingly bad) XML
<Names>
<Name>Matt</Name>
<Name>Stacy</Name>
<Names>
Only Stacy is added to Names in the array, wiping Matt in the process.
To fix this replace the following code
<?php
elseif ($dat[level] === $level && $dat[type] === "complete"){
$newarray[$dat[tag]]=$dat[value];
}
?>
with
<?php
elseif ($dat[level] === $level && $dat[type] === "complete"){
if (isset($newarray[$dat['tag']]) &&
is_array($newarray[$dat['tag']])){
$newarray[$dat['tag']][] = $dat['value'];
} elseif (isset($newarray[$dat['tag']]) &&
!is_array($newarray[$dat['tag']])){
$newarray[$dat['tag']] = array($newarray[$dat['tag']],
$dat['value']);
} else {
$newarray[$dat['tag']]=$dat['value'];
}
}?>
Oh, also, note that the $dat[level], etc, WILL generate warnings, and should be more correctly
written as $dat['level'].
The other thing I thought I should point out is that the array keys when created using
xml_parse_into_struct will be an UPPERCASE version of your existing element names. If case is
important, especially if you, like me, need mixedCase, do the following:
<?php
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser,XML_OPTION_CASE_FOLDING,0);
?>