c91fe14057146738b7a1fc9fee558b217eab4e92
2 # This should one day become the XML->(X)HTML parser
3 # Based on work by Jan Hidders and Magnus Manske
5 // the base class for an element
9 var $children = array();
13 echo "<LI> <B> Name: </B> $this->name";
15 echo '<LI> <B> Attributes: </B>';
16 foreach ($this->attrs
as $name => $value) {
17 echo "$name => $value; " ;
20 foreach ($this->children
as $child) {
21 if ( is_string($child) ) {
32 $ancStack = array(); // the stack with ancestral elements
34 // Three global functions needed for parsing, sorry guys
35 function wgXMLstartElement($parser, $name, $attrs) {
36 global $ancStack, $rootElem;
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;
45 array_push($ancStack[$nrAncs-1]->children
, &$ancStack[$nrAncs]);
47 // make extra copy of root element and alias it with the original
48 array_push($ancStack, &$ancStack[0]);
52 function wgXMLendElement($parser, $name) {
53 global $ancStack, $rootElem;
55 // pop element of stack
59 function wgXMLcharacterData($parser, $data) {
60 global $ancStack, $rootElem;
62 $data = trim ( $data ) ; // Don't add blank lines, they're no use...
64 // add to parent if parent exists
65 if ( $ancStack && $data != "" ) {
66 array_push($ancStack[count($ancStack)-1]->children
, $data);
71 # Here's the class that generates a nice tree
74 function &scanFile( $filename ) {
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');
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)));
91 xml_parser_free($xml_parser);
93 // return the remaining root element we copied in the beginning
100 $filename = 'sample.xml';
101 $result = $w->scanFile( $filename );