note 85102 deleted from function.xml-parse-into-struct by cmb

From: Date: Sun, 06 Oct 2019 08:28:48 +0000
Subject: note 85102 deleted from function.xml-parse-into-struct by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212528@lists.php.net to get a copy of this message
Note Submitter: POST at PSPAETH dot DE ---- I wrote a simple function which totally flattens any xml structure. You can then directly get the data or use regular expression functions to fetch data from the output. E.g., if the input is <gallery xmlns='http://www.pspaeth.de/joomlaPlugins/psg'> <g imageDir='einsatzGallerie'></g> <caption for="f1.jpg"}This is picture number 1</caption> <caption for="f2.jpg"}This is picture number 2</caption> </g> </gallery> the output will be an array: ['.gallery0@xmlns']=> ".gallery0@xmlns=http://www.pspaeth.de/joomlaPlugins/psg" ['.gallery0.g0@imageDir']=> ".gallery0.g0@imageDir=einsatzGallerie" ['.gallery0.g0.caption0@for']=> ".gallery0.g0.caption0@for=f1.jpg" ['.gallery0.g0.caption0']=> ".gallery0.g0.caption0=This is picture number 1" ['.gallery0.g0.caption1@for']=> ".gallery0.g0.caption1@for=f2.jpg" ['.gallery0.g0.caption1']=> ".gallery0.g0.caption1=This is picture number 2" Here the code: <?php function _xmlToArray($xml) { $parser = xml_parser_create('UTF-8'); // UTF-8 or ISO-8859-1 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, $xml, $values); xml_parser_free($parser); $return = array(); $stack = ''; $attrs = array(); $levelCounters = array(0); foreach($values as $val) { if($val['type'] == "open") { $ind = array_pop($levelCounters); $stack = $stack . "." . $val['tag'] . $ind; if ($val['attributes']) { foreach($val['attributes'] as $attrKey => $attrVal) $return[$stack . '@' . $attrKey] = $stack . '@' . $attrKey . "=" . $attrVal; } array_push($levelCounters,$ind+1); array_push($levelCounters,0); } elseif($val['type'] == "close") { $stack = substr($stack,0,strrpos($stack,'.')); } elseif($val['type'] == "complete") { $ind = array_pop($levelCounters); $stack = $stack . "." . $val['tag'] . $ind; if ($val['attributes']) { foreach($val['attributes'] as $attrKey => $attrVal) $return[$stack . '@' . $attrKey] = $stack . '@' . $attrKey . "=" . $attrVal; } $return[$stack] = $stack . "=" . $val['value']; $stack = substr($stack,0,strrpos($stack,'.')); array_push($levelCounters,$ind+1); } } return $return; } ?>

« previous php.notes (#212528) next »