search
HomeBackend DevelopmentPHP Tutorial用PHP&XML编制迷你搜索引擎(一)_PHP

一、认识XML

大家可能对XML还很陌生我这里不想系统的讲解XML为何许物也我只是对本文用到的一些概念进行一些介绍如果您已经使用过XML哪怕是初学者。您也可以跳过这章。

谈起XML
我不妨先给您一段我们熟悉的html的代码。

(1) html>

(2) title>page title/title>

(3) body>

(4) p>center>font color="red">TEXT/font>/center>/p>

(5) a href="www.yahoo.com">img src="yahoo.gif"/>/a>

(6) /body>

(7) /html>

上面这段代码从结构上就可以符合XML的规则。
他符合下面几个特点

1、引用同一个元素的时候
使用一致的大小写如center>/Center>就是不符合规定的

2、任何属性值
(如 href="????")要用"" 扩起来如a href=www.yahoo.com>就是不正确的

3、所有元素必须由打开
和关闭>标注组成元素应该形如body>/body>、或空元素img ... />

请注意结尾的
/> 少了/就是错误的代码

4、所有元素必须彼此嵌套
就像写程序的循环一样而且所有的元素必须嵌套于根元素之中如上面的代码所有的内容都嵌套于html>/html>之中。

5、元素名称
(即上面的body a p img等)应为字母开头其实最好就是一个英文单词请注意大小写。



怎么样
XML不是太烦吧你可以理解为他是一个很好的包含数据的树形的结构类型。

好了
大家来熟悉一下我们程序中用到的那个XML吧。



links>网络狂飙之谜你搜索引擎采用PHP和XML技术构建

web memo="memo1" url="">name1/web>

sub>电脑网络

web memo="nemo2">name2/web>

sub>程序设计语言

web memo="memo3">name3/web>

sub>PHP

web url="http://www.phpbuilder.com/" memo="[英文]PHP开发资源。">

www.phpbuilder.com/web>

web url="http://www.fokus.gmd.de" memo="[英文]PHP开发手册。 ">

PHP Manual













其实,它的结构相当简单,根元素就是links,sub代表着一个类别,web就是一个网站的信息,其中包含着属性,url代表网站的联接,memo为备注信息,????中包含的为元素的数据在这里就是类别和网站的名称。请注意,他可是符合我上面的规定的。

在第1行加上
(没有会出错)另存为xyz.xml用IE5以上的浏览器打开看看。

怎么样
他的树形的结构一览无余。

那么我们的mini的搜索引擎为什么要使用他呢。第一个原因就是我在奥索网还不能使用mysql
(真惭愧)其次对于小数据量的搜索引擎来说它的数据量很小如果用数据库来做效率未必有多高。最重要的一点是他维护起来相当的简单减少了人力并且不用编写繁琐的数据库的维护的程序例如我们要添加一个类别或者网页只要编辑文本的文件加上一个web>???/web>或是sub>????/sub>就可以了而且如果想把一个类别移动到另一个地方的话我们只要将这一部分的subctrl-x,ctrl-v不就行了树形结构吗

其实
XML的功能我只用到了一点的皮毛以后我会奉献给大家更深入的文章。



二、PHP如何解析XML

本章的内容借鉴自网易虚拟社区我懒得敲了加以修改。

XML解析器的两种基本类型




基于树型的解析器
将XML文档转换成树型结构。这类解析器分析整篇文章同时提供一个API来访问所产生树的每个元素。其通用的标准为DOM文档对象模式。 使用过Javascript可能用过XMLDOM。



基于事件的解析器
将XML文档视为一系列的事件。当一个特殊事件发生时解析器将调用开发者提供的函数来处理。

基于事件的解析器有一个XML文档的数据集中视图
也就是说它集中在XML文档的数据部分而不是其结构。这些解析器从头到尾处理文档并将类似于元素的开始、元素的结尾、特征数据的开始等等事件通过回调callback函数报告

给应用程序。以下是一个
"Hello-World"的XML文档范例



greeting>

Hello World

/greeting>



基于事件的解析器将报告为三个事件




开始元素
greeting

CDATA项的开始
值为Hello World

结束元素
greeting

不像基于树型的解析器
基于事件的解析器不产生描述文档的结构。在CDATA项中基于事件的解析器不会让你得到父元素greeting的信息。

然而
它提供一个更底层的访问这就使得可以更好地利用资源和更快地访问。通过这种方式就没有必要将整个文档放入内存而事实上整个文档甚至可以大于实际内存值。



准备



用于产生XML解析器实例的函数为xml_parser_create
()。该实例将用于以后的所有函数。这个思路非常类似于PHP中MySQL函数的连接标记。在解析文档前基于事件的解析器通常要求你注册回调函数用于特定的事件发生时调用。Expat没有例外事件它定义了如下七个可能事件





对象 XML解析函数 描述



元素 xml_set_element_handler
() 元素的开始和结束



字符数据 xml_set_character_data_handler
() 字符数据的开始



外部实体 xml_set_external_entity_ref_handler
() 外部实体出现



未解析外部实体 xml_set_unparsed_entity_decl_handler
() 未解析的外部实体

出现



处理指令 xml_set_processing_instruction_handler
() 处理指令的出现



记法声明 xml_set_notation_decl_handler
() 记法声明的出现



默认 xml_set_default_handler
() 其它没有指定处理函数的事件



所有的回调函数必须将解析器的实例作为其第一个参数
此外还有其它参数



更详细的说明可以参见PHP的说明。



下列用来显示 XML 元素结构
(Element Structure)





下面的范例摘自PHP手册范例


他是我们的搜索引擎的基本结构
但是我就不加以注释了因为我们下一章将会介绍。


$file
= "data.xml";

$depth
= array();



function startElement($parser, $name, $attrs)

{

global $depth;

for ($i = 0; $i $depth[$parser]; $i++) {

print " ";

}

print "$name

"
;

$depth
[$parser]++;

}



function endElement($parser, $name, $attrs)

{

global $depth;

$depth
[$parser]--;

}



$xml_parser
= xml_parser_create();

xml_set_element_handler
($xml_parser, "startElement", "endElement");

if (!($fp = fopen($file, "r"))) {

die("could not open XML input");

}

while ($data = fread($fp, 4096)) {

if (!xml_parse($xml_parser, $data, feof($fp))) {

die(sprintf("XML error: %s at line %d",

xml_error_string
(xml_get_error_code($xml_parser)),

xml_get_current_line_number
($xml_parser)));

}

}

xml_parser_free
($xml_parser);

?>

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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),