Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?
- class XmlElement {
- var $name;
- var $attributes;
- var $content;
- var $children;
- };
- function xml_to_object($xml) {
- $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, $tags);
- xml_parser_free($parser);
- $elements = array(); // the currently filling [child] XmlElement array
- $stack = array();
- foreach ($tags as $tag) {
- $index = count($elements);
- if ($tag['type'] == "complete" || $tag['type'] == "open") {
- $elements[$index] = new XmlElement;
- $elements[$index]->name = $tag['tag'];
- $elements[$index]->attributes = $tag['attributes'];
- $elements[$index]->content = $tag['value'];
- if ($tag['type'] == "open") { // push
- $elements[$index]->children = array();
- $stack[count($stack)] = &$elements;
- $elements = &$elements[$index]->children;
- }
- }
- if ($tag['type'] == "close") { // pop
- $elements = &$stack[count($stack) - 1];
- unset($stack[count($stack) - 1]);
- }
- }
- return $elements[0]; // the single top-level element
- }
- // For example:
- $xml = file_get_contents('1.xml');
- print_r(xml_to_object($xml));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement