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

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

WBOY
WBOYOriginal
2016-06-01 12:35:12866browse

三、一个最简单的用PHP显示XML的范例



下面的程序是将解析XML并按照树形结构输出至浏览器并显示每层的元素总数。

__________________________________________________________









$file
= "demo.xml";// 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)

//遇到了开元素标记如就执行这一段,

//$name=a,$attrs为一个属性数组

{

global $level,$levelcount,$maxlevel;



$level += 1;

if($level>$maxlevel)$maxlevel=$level;

$levelcount[$level]+=1;

echo "

";

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



echo "".trim($name)." ";



while ( list( $key, $val ) = each( $attrs ) ) { //显示属性

echo "$key => $val; ";

}



}



function stop_element($parser, $name)

//遇到了开元素标记如

Statement:
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