note 72227 deleted from function.xml-parse-into-struct by cmb
| From: | cmb@php.net | Date: | Sun, 21 Oct 2018 09:32:19 +0000 |
| Subject: | note 72227 deleted from function.xml-parse-into-struct by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-209476@lists.php.net to get a copy of this message | ||
Note Submitter: amish
----
Previous parser worked great for me, except a few issues. It did not work well if the element has
attributes. I had a huge xml with so many elements, and attributes. Somehow, it mixed up my array,
and messed up the keys. Hope following code help fix those issues....
$xml_response = "
<test>
<item>
<name att=\"this should show up\">Item1</name>
<id>item_1</id>
<description> This is Item 1</description>
<quantity>10</quantity>
<navigation website='site1'>test1</navigation>
<navigation website='site2'>test2</navigation>
</item>
</test>
"
$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,$xml_response,$values,$tags);
xml_parser_free($parser);
$params = array();
$level = array();
foreach ($values as $xml_elem) {
$start_level = 1;
if ($xml_elem['type'] == 'open') {
if (array_key_exists('attributes',$xml_elem)) {
list($level[$xml_elem['level']],$extra) =
array_values($xml_elem['attributes']);
} else {
$level[$xml_elem['level']] = $xml_elem['tag'];
}
$name_array = array();
$i=0;
}
if ($xml_elem['type'] == 'complete') {
if(!in_array($xml_elem['tag'], $name_array)){
array_push($name_array, $xml_elem['tag']);
$i=0;
}else{
$i++;
}
$php_stmt = '$params';
while($start_level < $xml_elem['level']) {
$php_stmt .= '[$level['.$start_level.']]';
$test = $php_stmt;
$start_level++;
}
$php_stmt .= '[$xml_elem[\'tag\']][$i] =
$xml_elem[\'value\'];';
if(isset($xml_elem['attributes'])){
foreach ($xml_elem['attributes'] as $key=>$va){
$attribute = '';
$new_stmt = '';
$attribute = "".$i."_attribute_".$key."";
$new_stmt .= $test.'[$xml_elem[\'tag\']][$attribute] = $va;';
eval($new_stmt);
}
}
eval($php_stmt);
$start_level--;
}
if ($xml_elem['type'] == 'close') {
array_pop($level);
}
}