note 38739 added to function.xml-parser-create

From: Date: Mon, 05 Jan 2004 15:00:04 +0000
Subject: note 38739 added to function.xml-parser-create
Groups: php.notes 
Request: Send a blank email to php-notes+get-62947@lists.php.net to get a copy of this message
thought I'd share this small piece of PHP code that prepares a proper array from XML Data (uses xml_parse_into_struct to get a raw array) features : 1) can easily adjust to multiple levels 2) simple. <code> $file = "data.xml"; $xml_parser = xml_parser_create(); if (!($fp = fopen($file, "r"))) { die("could not open XML input"); } $data = fread($fp, filesize($file)); fclose($fp); xml_parse_into_struct($xml_parser, $data, $vals, $index); xml_parser_free($xml_parser); $params = array(); $level = array(); foreach ($vals as $xml_elem) { 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']; } } if ($xml_elem['type'] == 'complete') { $start_level = 1; $php_stmt = '$params'; while($start_level < $xml_elem['level']) { $php_stmt .= '[$level['.$start_level.']]'; $start_level++; } $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];'; eval($php_stmt); } } echo "<pre>"; print_r ($params); echo "</pre>"; </code> Example : I/P XML ... <country id="ZZ"> <name>My Land</name> <location>15E</location> <area>40000</area> <state1> <name>Hi State</name> <area>1000</area> <population>2000</population> <city1> <location>13E</location> <population>500</population> <area>500</area> </city1> <city2> <location>13E</location> <population>500</population> <area>5000</area> </city2> </state1> <state2> <name>Low State</name> <area>3000</area> <population>20000</population> <city1> <location>15E</location> <population>5000</population> <area>1500</area> </city1> </state2> </country> O/P Array : Array ( [ZZ] => Array ( [NAME] => My Land [LOCATION] => 15E [AREA] => 40000 [STATE1] => Array ( [NAME] => Hi State [AREA] => 1000 [POPULATION] => 2000 [CITY1] => Array ( [LOCATION] => 13E [POPULATION] => 500 [AREA] => 500 ) [CITY2] => Array ( [LOCATION] => 13E [POPULATION] => 500 [AREA] => 5000 ) ) [STATE2] => Array ( [NAME] => Low State [AREA] => 3000 [POPULATION] => 20000 [CITY1] => Array ( [LOCATION] => 15E [POPULATION] => 5000 [AREA] => 1500 ) ) ) ) ---- Manual Page -- http://www.php.net/manual/en/function.xml-parser-create.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+38739 Delete -- http://master.php.net/manage/user-notes.php?action=delete+38739&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+38739&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#62947) next »