note 65332 deleted from function.xml-parse-into-struct by cmb
| From: | cmb@php.net | Date: | Sun, 06 Oct 2019 08:28:10 +0000 |
| Subject: | note 65332 deleted from function.xml-parse-into-struct by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212526@lists.php.net to get a copy of this message | ||
Note Submitter: donna at coloma dot com
----
I needed a very simple parser for a set of name-value pairs to be stored in a single database field.
I started with the mold example, paired it down, picked up the "id" attributes. Perhaps it
will be useful for someone else.
<?php
/* simple conversion for name-value fields */
$xmlInput = "<?xml version=\"1.0\"?>
<mcw_settings>
<field id=\"imageAlign\">left</field>
<field id=\"caption\">What a nice picture.</field>
</mcw_settings>";
$desiredResult = array (
'imageAlign' => "left",
'caption' => "What a nice picture."
);
function parseFields ($data)
{
// read the XML database of fields
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, $data, $values, $tags);
xml_parser_free($parser);
$fields = null;
// loop through the structures
$fieldIndices = $tags['field'];
for ( $i=0; $i < count($fieldIndices); $i++ ) {
$fieldInfo = $values[$fieldIndices[$i]];
$fields[$fieldInfo['attributes']['id']] = $fieldInfo['value'];
}
return $fields;
}
$test = parseFields($xmlInput);
echo "** Result:\n";
print_r($test);
?>