note 72227 added to function.xml-parse-into-struct
| From: | amish at osu1 dot php dot net | Date: | Mon, 08 Jan 2007 17:21:41 +0000 |
| Subject: | note 72227 added to function.xml-parse-into-struct | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-121454@lists.php.net to get a copy of this message | ||
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);
}
}
----
Server IP: 216.194.113.175
Probable Submitter: 216.28.180.158
----
Manual Page -- http://www.php.net/manual/en/function.xml-parse-into-struct.php
Edit -- https://master.php.net/note/edit/72227
Del: integrated -- https://master.php.net/note/delete/72227/integrated
Del: useless -- https://master.php.net/note/delete/72227/useless
Del: bad code -- https://master.php.net/note/delete/72227/bad+code
Del: spam -- https://master.php.net/note/delete/72227/spam
Del: non-english -- https://master.php.net/note/delete/72227/non-english
Del: in docs -- https://master.php.net/note/delete/72227/in+docs
Del: other reasons-- https://master.php.net/note/delete/72227
Reject -- https://master.php.net/note/reject/72227
Search -- https://master.php.net/manage/user-notes.php