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