1 | <?php |
||
8 | class xml2Array |
||
9 | { |
||
10 | |||
11 | public $stack = []; |
||
12 | public $stack_ref; |
||
13 | public $arrOutput = []; |
||
14 | public $resParser; |
||
15 | public $strXmlData; |
||
16 | |||
17 | public function push_pos(&$pos) |
||
18 | { |
||
19 | $this->stack[count($this->stack)] =& $pos; |
||
20 | $this->stack_ref =& $pos; |
||
21 | } |
||
22 | |||
23 | public function pop_pos() |
||
24 | { |
||
25 | unset($this->stack[count($this->stack) - 1]); |
||
26 | $this->stack_ref =& $this->stack[count($this->stack) - 1]; |
||
27 | } |
||
28 | |||
29 | public function parse($strInputXML) |
||
30 | { |
||
31 | |||
32 | $this->resParser = xml_parser_create("UTF-8"); |
||
33 | xml_set_object($this->resParser, $this); |
||
34 | xml_set_element_handler($this->resParser, "tagOpen", "tagClosed"); |
||
35 | |||
36 | xml_set_character_data_handler($this->resParser, "tagData"); |
||
37 | |||
38 | $this->push_pos($this->arrOutput); |
||
39 | |||
40 | $this->strXmlData = xml_parse($this->resParser, $strInputXML); |
||
41 | if (!$this->strXmlData) { |
||
42 | die(sprintf( |
||
43 | "XML error: %s at line %d", |
||
44 | xml_error_string(xml_get_error_code($this->resParser)), |
||
45 | xml_get_current_line_number($this->resParser) |
||
46 | )); |
||
47 | } |
||
48 | |||
49 | xml_parser_free($this->resParser); |
||
50 | |||
51 | return $this->arrOutput; |
||
52 | } |
||
53 | |||
54 | public function tagOpen($parser, $name, $attrs) |
||
55 | { |
||
56 | if (isset($this->stack_ref[$name])) { |
||
57 | if (!isset($this->stack_ref[$name][0])) { |
||
58 | $tmp = $this->stack_ref[$name]; |
||
59 | unset($this->stack_ref[$name]); |
||
60 | $this->stack_ref[$name][0] = $tmp; |
||
61 | } |
||
62 | $cnt = count($this->stack_ref[$name]); |
||
63 | $this->stack_ref[$name][$cnt] = []; |
||
64 | if (isset($attrs)) { |
||
65 | $this->stack_ref[$name][$cnt] = $attrs; |
||
66 | } |
||
67 | $this->push_pos($this->stack_ref[$name][$cnt]); |
||
68 | } else { |
||
69 | $this->stack_ref[$name] = []; |
||
70 | if (isset($attrs)) { |
||
71 | $this->stack_ref[$name] = $attrs; |
||
72 | } |
||
73 | $this->push_pos($this->stack_ref[$name]); |
||
74 | } |
||
75 | } |
||
76 | |||
77 | public function tagData($parser, $tagData) |
||
78 | { |
||
79 | if (mb_trim($tagData)) { |
||
80 | if (isset($this->stack_ref['DATA'])) { |
||
81 | $this->stack_ref['DATA'] .= $tagData; |
||
82 | } else { |
||
83 | $this->stack_ref['DATA'] = $tagData; |
||
84 | } |
||
85 | } |
||
86 | } |
||
87 | |||
88 | public function tagClosed($parser, $name) |
||
89 | { |
||
90 | $this->pop_pos(); |
||
91 | } |
||
92 | } |
||
93 |