e4cf4c2bc03fdcea60e8461838d61374527e99f8
[lhc/web/wiklou.git] / includes / ParserXML.php
1 <?
2 /**
3 * This should one day become the XML->(X)HTML parser
4 * Based on work by Jan Hidders and Magnus Manske
5 */
6
7 /**
8 * the base class for an element
9 */
10 class element {
11 var $name = '';
12 var $attrs = array();
13 var $children = array();
14
15 function myPrint() {
16 echo '<UL>';
17 echo "<LI> <B> Name: </B> $this->name";
18 // print attributes
19 echo '<LI> <B> Attributes: </B>';
20 foreach ($this->attrs as $name => $value) {
21 echo "$name => $value; " ;
22 }
23 // print children
24 foreach ($this->children as $child) {
25 if ( is_string($child) ) {
26 echo '<LI> '.$child;
27 } else {
28 $child->myPrint();
29 }
30 }
31 echo '</UL>';
32 }
33
34 }
35
36 $ancStack = array(); // the stack with ancestral elements
37
38 // Three global functions needed for parsing, sorry guys
39 function wgXMLstartElement($parser, $name, $attrs) {
40 global $ancStack, $rootElem;
41
42 $newElem = new element;
43 $newElem->name = $name;
44 $newElem->attrs = $attrs;
45 array_push($ancStack, $newElem);
46 // add to parent if parent exists
47 $nrAncs = count($ancStack)-1;
48 if ( $nrAncs > 0 ) {
49 array_push($ancStack[$nrAncs-1]->children, &$ancStack[$nrAncs]);
50 } else {
51 // make extra copy of root element and alias it with the original
52 array_push($ancStack, &$ancStack[0]);
53 }
54 }
55
56 function wgXMLendElement($parser, $name) {
57 global $ancStack, $rootElem;
58
59 // pop element of stack
60 array_pop($ancStack);
61 }
62
63 function wgXMLcharacterData($parser, $data) {
64 global $ancStack, $rootElem;
65
66 $data = trim ( $data ) ; // Don't add blank lines, they're no use...
67
68 // add to parent if parent exists
69 if ( $ancStack && $data != "" ) {
70 array_push($ancStack[count($ancStack)-1]->children, $data);
71 }
72 }
73
74
75 /**
76 * Here's the class that generates a nice tree
77 * package parserxml
78 */
79 class xml2php {
80
81 function &scanFile( $filename ) {
82 global $ancStack;
83 $ancStack = array();
84
85 $xml_parser = xml_parser_create();
86 xml_set_element_handler($xml_parser, 'wgXMLstartElement', 'wgXMLendElement');
87 xml_set_character_data_handler($xml_parser, 'wgXMLcharacterData');
88 if (!($fp = fopen($filename, 'r'))) {
89 die('could not open XML input');
90 }
91 while ($data = fread($fp, 4096)) {
92 if (!xml_parse($xml_parser, $data, feof($fp))) {
93 die(sprintf("XML error: %s at line %d",
94 xml_error_string(xml_get_error_code($xml_parser)),
95 xml_get_current_line_number($xml_parser)));
96 }
97 }
98 xml_parser_free($xml_parser);
99
100 // return the remaining root element we copied in the beginning
101 return $ancStack[0];
102 }
103
104 }
105
106 $w = new xml2php;
107 $filename = 'sample.xml';
108 $result = $w->scanFile( $filename );
109 $result->myPrint();
110
111 return 0;
112
113 ?>