3 * This should one day become the XML->(X)HTML parser
4 * Based on work by Jan Hidders and Magnus Manske
8 * the base class for an element
13 var $children = array();
17 echo "<LI> <B> Name: </B> $this->name";
19 echo '<LI> <B> Attributes: </B>';
20 foreach ($this->attrs
as $name => $value) {
21 echo "$name => $value; " ;
24 foreach ($this->children
as $child) {
25 if ( is_string($child) ) {
36 $ancStack = array(); // the stack with ancestral elements
38 // Three global functions needed for parsing, sorry guys
39 function wgXMLstartElement($parser, $name, $attrs) {
40 global $ancStack, $rootElem;
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;
49 array_push($ancStack[$nrAncs-1]->children
, &$ancStack[$nrAncs]);
51 // make extra copy of root element and alias it with the original
52 array_push($ancStack, &$ancStack[0]);
56 function wgXMLendElement($parser, $name) {
57 global $ancStack, $rootElem;
59 // pop element of stack
63 function wgXMLcharacterData($parser, $data) {
64 global $ancStack, $rootElem;
66 $data = trim ( $data ) ; // Don't add blank lines, they're no use...
68 // add to parent if parent exists
69 if ( $ancStack && $data != "" ) {
70 array_push($ancStack[count($ancStack)-1]->children
, $data);
76 * Here's the class that generates a nice tree
81 function &scanFile( $filename ) {
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');
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)));
98 xml_parser_free($xml_parser);
100 // return the remaining root element we copied in the beginning
107 $filename = 'sample.xml';
108 $result = $w->scanFile( $filename );