1 | <?php |
---|
2 | // ne pas oublier de crediter |
---|
3 | |
---|
4 | class xmlParser{ |
---|
5 | var $xml_obj = null; |
---|
6 | var $output = array(); |
---|
7 | var $attrs; |
---|
8 | |
---|
9 | function xmlParser(){ |
---|
10 | $this->xml_obj = xml_parser_create(); |
---|
11 | xml_set_object($this->xml_obj,$this); |
---|
12 | xml_set_character_data_handler($this->xml_obj, 'dataHandler'); |
---|
13 | xml_set_element_handler($this->xml_obj, "startHandler", "endHandler"); |
---|
14 | } |
---|
15 | |
---|
16 | function parse($path){ |
---|
17 | if (!($fp = fopen($path, "r"))) { |
---|
18 | die("Cannot open XML data file: $path"); |
---|
19 | return false; |
---|
20 | } |
---|
21 | |
---|
22 | while ($data = fread($fp, 4096)) { |
---|
23 | if (!xml_parse($this->xml_obj, $data, feof($fp))) { |
---|
24 | die(sprintf("XML error: %s at line %d", |
---|
25 | xml_error_string(xml_get_error_code($this->xml_obj)), |
---|
26 | xml_get_current_line_number($this->xml_obj))); |
---|
27 | xml_parser_free($this->xml_obj); |
---|
28 | } |
---|
29 | } |
---|
30 | |
---|
31 | return true; |
---|
32 | } |
---|
33 | |
---|
34 | function startHandler($parser, $name, $attribs){ |
---|
35 | $_content = array(); |
---|
36 | $_content['name'] = $name; |
---|
37 | if(!empty($attribs)) |
---|
38 | $_content['attrs'] = $attribs; |
---|
39 | array_push($this->output, $_content); |
---|
40 | } |
---|
41 | |
---|
42 | function dataHandler($parser, $data){ |
---|
43 | if(!empty($data) && $data!="\n") { |
---|
44 | $_output_idx = count($this->output) - 1; |
---|
45 | $this->output[$_output_idx]['content'] .= $data; |
---|
46 | } |
---|
47 | } |
---|
48 | |
---|
49 | function endHandler($parser, $name){ |
---|
50 | if(count($this->output) > 1) { |
---|
51 | $_data = array_pop($this->output); |
---|
52 | $_output_idx = count($this->output) - 1; |
---|
53 | $add = array(); |
---|
54 | if(!$this->output[$_output_idx]['child']) |
---|
55 | $this->output[$_output_idx]['child'] = array(); |
---|
56 | array_push($this->output[$_output_idx]['child'], $_data); |
---|
57 | } |
---|
58 | } |
---|
59 | } |
---|
60 | ?> |
---|