note 35708 added to function.xml-parse

From: Date: Thu, 11 Sep 2003 17:11:03 +0000
Subject: note 35708 added to function.xml-parse
Groups: php.notes 
Request: Send a blank email to php-notes+get-56163@lists.php.net to get a copy of this message
I've created a parser that returns an object based on a xml document. example: <?xml version="1.0" encoding="ISO-8859-1" ?> <country name="sweden"> <city name="stockholm"> <user>Adam</user> <user>Eve</user> </city> <city name="göteborg"> <user>God</user> </city> </country> <country name="usa"> <city name="new york"> <user>Clinton</user> <user>Bush</user> </city> </country> generates the following object structure: [country] => Array ( [0] => stdClass Object ( [name] => sweden [city] => Array ( [0] => stdClass Object ( [name] => stockholm [user] => Array ( [0] => Adam [1] => Eve ) ) [1] => stdClass Object ( [name] => göteborg [user] => God ) ) ) [1] => stdClass Object ( [name] => usa [city] => stdClass ( [name] => new york [user] => Array ( [0] => Clinton [1] => Bush ) ) ) ) Here is the code: class XMLParser { var $path; var $result; function XMLParser($encoding, $data) { $this->path = "\$this->result"; $this->index = 0; $xml_parser = xml_parser_create($encoding); xml_set_object($xml_parser, &$this); xml_set_element_handler($xml_parser, 'startElement', 'endElement'); xml_set_character_data_handler($xml_parser, 'characterData'); xml_parse($xml_parser, $data, true); xml_parser_free($xml_parser); } function startElement($parser, $tag, $attributeList) { $this->path .= "->".$tag; eval("\$data = ".$this->path.";"); if (is_array($data)) { $index = sizeof($data); $this->path .= "[".$index."]"; } else if (is_object($data)) { eval($this->path." = array(".$this->path.");"); $this->path .= "[1]"; } foreach($attributeList as $name => $value) eval($this->path."->".$name. " = '".trim($value)."';"); } function endElement($parser, $tag) { $this->path = substr($this->path, 0, strrpos($this->path, "->")); } function characterData($parser, $data) { eval($this->path." = '".trim($data)."';"); } } enjoy! And please make it better if you can ;-) ---- Manual Page -- http://www.php.net/manual/en/function.xml-parse.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+35708 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+35708&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+35708&report=yes

« previous php.notes (#56163) next »