Home > Backend Development > PHP Tutorial > 用PHP&XML编制迷你搜索引擎(三)_PHP

用PHP&XML编制迷你搜索引擎(三)_PHP

WBOY
Release: 2016-06-01 12:35:13
Original
733 people have browsed it

四、在第三章程序的基础上可以显示一段子树。

同第二章的代码我就不再注释了。

下面的代码是我们的迷你搜索引擎的基础。

因为
要显示出一个字类别如程序设计->PHP->的信息就要用到他。

我们依照元素的层数和他在当层的第几号来对他进行定位





links
01

+----web 11

+----sub 12

| +----web 21

| +----sub 22

| | +----web 31

| | +----sub 32



:

:

:



__________________________________________________________

html>

body>







// XML文件

$file = "demo.xml";







// 解析XML文件的函数

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){ //判断是否在子树的范围内 $hide==FALSE 为在

if($level==$lev&&$levelcount[$level]==$num)$hide=FALSE;

}else{

if($level
}





if(!$hide){

echo "

";

for($i=1;$i
if($level-$lev>0)echo"+----";



echo "".

//加上每个元素节点的联接

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);





?>

/body>

/html>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template