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