Bug 480: remove extra spacing from TOC indentation areas
[mediawiki.git] / includes / ParserXML.php
blob5b08a2bc1013563c9c3e80b275e6895b85b8ff78
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 */
8 /**
9 * the base class for an element
10 * @package MediaWiki
12 class element {
13 var $name = '';
14 var $attrs = array();
15 var $children = array();
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; " ;
25 // print children
26 foreach ($this->children as $child) {
27 if ( is_string($child) ) {
28 echo '<LI> '.$child;
29 } else {
30 $child->myPrint();
33 echo '</UL>';
38 $ancStack = array(); // the stack with ancestral elements
40 // Three global functions needed for parsing, sorry guys
41 function wgXMLstartElement($parser, $name, $attrs) {
42 global $ancStack, $rootElem;
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]);
58 function wgXMLendElement($parser, $name) {
59 global $ancStack, $rootElem;
61 // pop element of stack
62 array_pop($ancStack);
65 function wgXMLcharacterData($parser, $data) {
66 global $ancStack, $rootElem;
68 $data = trim ( $data ) ; // Don't add blank lines, they're no use...
70 // add to parent if parent exists
71 if ( $ancStack && $data != "" ) {
72 array_push($ancStack[count($ancStack)-1]->children, $data);
77 /**
78 * Here's the class that generates a nice tree
79 * package parserxml
80 * @package MediaWiki
82 class xml2php {
84 function &scanFile( $filename ) {
85 global $ancStack;
86 $ancStack = array();
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');
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)));
101 xml_parser_free($xml_parser);
103 // return the remaining root element we copied in the beginning
104 return $ancStack[0];
109 $w = new xml2php;
110 $filename = 'sample.xml';
111 $result = $w->scanFile( $filename );
112 $result->myPrint();
114 return 0;