krot

XML parser

Jul 29th, 2016
75
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?
  2. class XmlElement {
  3.   var $name;
  4.   var $attributes;
  5.   var $content;
  6.   var $children;
  7. };
  8.  
  9. function xml_to_object($xml) {
  10.   $parser = xml_parser_create();
  11.   xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  12.   xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  13.   xml_parse_into_struct($parser, $xml, $tags);
  14.   xml_parser_free($parser);
  15.  
  16.    
  17.    
  18.   $elements = array();  // the currently filling [child] XmlElement array
  19.   $stack = array();
  20.   foreach ($tags as $tag) {
  21.     $index = count($elements);
  22.     if ($tag['type'] == "complete" || $tag['type'] == "open") {
  23.       $elements[$index] = new XmlElement;
  24.       $elements[$index]->name = $tag['tag'];
  25.       $elements[$index]->attributes = $tag['attributes'];
  26.       $elements[$index]->content = $tag['value'];
  27.       if ($tag['type'] == "open") {  // push
  28.         $elements[$index]->children = array();
  29.         $stack[count($stack)] = &$elements;
  30.         $elements = &$elements[$index]->children;
  31.       }
  32.     }
  33.     if ($tag['type'] == "close") {  // pop
  34.       $elements = &$stack[count($stack) - 1];
  35.       unset($stack[count($stack) - 1]);
  36.     }
  37.   }
  38.   return $elements[0];  // the single top-level element
  39. }
  40.  
  41. // For example:
  42. $xml = file_get_contents('1.xml');
  43. print_r(xml_to_object($xml));
RAW Paste Data