4. a subtree is displayed on the basis of the procedures in chapter 3. I will not comment out the code in the second chapter. The following code is the basis of our mini search engine. on the basis of chapter 3 program, we can display a subtree.
I will not comment out the code in the second chapter.
The following code is the basis of our mini search engine.
Because it is necessary to display the information of a word category (such as program design-> PHP->.
We locate the element based on the number of layers of the element and the number of the layer on which it is located.
For example:
Links (0, 1)
+ ---- Web (1, 1)
+ ---- Sub (1, 2)
| + ---- Web (2, 1)
| + ---- Sub (2, 2)
| + ---- Web (3, 1)
| + ---- Sub (3, 2)
:
:
:
__________________________________________________________
// XML file
$ File = "demo. xml ";
// Functions used to parse XML files
Function xml_parse_from_file ($ parser, $ file)
{
If (! File_exists ($ file ))
{
Die ("Can't find file" $ file ".");
}
If (! ($ Fp = @ fopen ($ file, "r ")))
{
Die ("Can't open file" $ file ".");
}
While ($ data = fread ($ fp, 4096 ))
{
If (! Xml_parse ($ parser, $ data, feof ($ fp )))
{
Return (false );
}
}
Fclose ($ fp );
Return (true );
}
Function start_element ($ parser, $ name, $ attrs)
{
Global $ level, $ levelcount, $ maxlevel, $ hide, $ lev, $ num, $ PHP_SELF;
$ Level + = 1;
If ($ level> $ maxlevel) $ maxlevel = $ level;
$ Levelcount [$ level] + = 1;
If ($ hide) {// Determine whether the sub-tree is in the range of $ hide = FALSE
If ($ level = $ lev& & $ levelcount [$ level] = $ num) $ hide = FALSE;
} Else {
If ($ level <= $ lev) $ hide = TRUE;
}
If (! $ Hide ){
Echo"
";
For ($ I = 1; $ I <= ($ level-1-$ EV); $ I ++) echo "| ";
If ($ level-$ lev> 0) echo "+ ----";
Echo "".
// Add the join of each element node
Trim ($ name )."";
While (list ($ key, $ val) = each ($ attrs )){
Echo "$ key => $ val ;";
}
}
}
Function stop_element ($ parser, $ name)
{
Global $ level;
$ Level-= 1;
}
Function data ($ parser, $ data)
{
Global $ level, $ hide;
If (! $ Hide)
If (trim ($ data )! = ""){
Echo trim ($ data );
}
}
// Main start
Global $ hide, $ lev, $ num, $ PHP_SELF;
$ Level =-1;
$ Hide = TRUE;
Echo"
Root
";
If ($ lev= = "") {$ lev= 0; $ num = 1 ;}
$ Parser = xml_parser_create ();
Xml_set_element_handler ($ parser, "start_element", "stop_element ");
Xml_set_character_data_handler ($ parser, "data ");
Xml_parser_set_option ($ parser, XML_OPTION_CASE_FOLDING, 0 );
$ Ret = xml_parse_from_file ($ parser, $ file );
If (! $ Ret)
{
Die (sprintf ("XML error: % s at line % d ",
Xml_error_string (xml_get_error_code ($ parser )),
Xml_get_current_line_number ($ parser )));
}
Xml_parser_free ($ parser );
?>