3 * This should one day become the XML->(X)HTML parser
4 * Based on work by Jan Hidders and Magnus Manske
9 * the base class for an element
15 var $children = array();
19 echo "<LI> <B> Name: </B> $this->name";
21 echo '<LI> <B> Attributes: </B>';
22 foreach ($this->attrs
as $name => $value) {
23 echo "$name => $value; " ;
26 foreach ($this->children
as $child) {
27 if ( is_string($child) ) {
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;
51 array_push($ancStack[$nrAncs-1]->children
, &$ancStack[$nrAncs]);
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
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);
78 * Here's the class that generates a nice tree
84 function &scanFile( $filename ) {
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
110 $filename = 'sample.xml';
111 $result = $w->scanFile( $filename );