当前位置: 首页 > 网络学院 > 服务端脚本教程 > PHP > XML Expat Parser
The built-in Expat parser makes it possible to process XML documents in PHP.
内置的Expat解析器可以使XML文档在PHP中运行。
XML is used to describe data and to focus on what data is. An XML file describes the structure of the data.
XML是用来描述数据及其本身的属性的。一个XML文件描述了数据结构。
In XML, no tags are predefined. You must define your own tags.
在XML中,无需预先定义标签[tag],你可以自定义标签。
If you want to learn more about XML, please visit our XML tutorial.
如果你先学习关于XML的更多知识,请访问我们的XML教程。
To read and update - create and manipulate - an XML document, you will need an XML parser.
为了对一个XML文档进行读取/修改、创建/操作,你需要一个XML解析器。
There are two basic types of XML parsers:
下面介绍一下XML解析器的两种基本类型:
The Expat parser is an event-based parser.
Expat解析器是一个“事件”解析器[Event-based parser]。
Event-based parsers focus on the content of the XML documents, not its structure. Because of this, event based parsers can access data faster than Tree-based parsers.
“事件”解析器主要针对XML文档的内容进行解析,而不是它的结构。由于这个原因“事件”解析器对数据的访问速度要比“树型”解析器更快。
Look at the following XML fraction:
看下面这个XML片段:
<from>Jani</from> |
An event-based parser reports the XML above as a series of three events:
“事件解析器”通过三个方面的事件对上述XML进行陈述:
The XML example above contains well-formed XML. However, the example is not valid XML, because there is no Document Type Definition (DTD) associated with it.
上述的XML案例包含了格式完整的XML。然而,这个案例并不是一个有效的XML,因为它并未包含文档类型定义[Document Type Definition (DTD)]。
However, this makes no difference when using the Expat parser. Expat is a non-validating parser, and ignores any DTDs.
然而,这和使用Expat解析器并不存在什么不同。Expat解析器本身就不对有效性进行验证,它将忽略所有的DTD。
As an event-based, non-validating XML parser, Expat is fast and small, and a perfect match for PHP web applications.
作为一个“事件”解析器,Expat并不对XML进行有效性的验证;但它的速度更快,且所占的空间更小,并且它与PHP的网络应用程序匹配的天衣无缝。
Note: XML documents must be well-formed or Expat will generate an error.
注意:XML文档必须具有完整的格式,否则,Expat将产生一个错误。
The XML Expat parser functions are part of the PHP core. There is no installation needed to use these functions.
XML Expat解析器函数是PHP核心的一部分,所以无需安装。
The XML file below will be used in our example:
我们用下面的例子展示XML文件:
<?xml version="1.0" encoding="ISO-8859-1"?> |
We want to initialize the XML parser in PHP, define some handlers for different XML events, and then parse the XML file.
我们打算在PHP中安装XML解析器,为不同的XML事件定义不同的处理方法,然后对XML文件进行解析。
<?php //Initialize the XML parser //Function to use at the start of an element //Function to use at the end of an element //Function to use when finding character data //Specify element handler //Specify data handler //Open XML file //Read data //Free the XML parser ?> |
The output of the code above will be:
上述代码将输出下面的结果:
-- Note -- |
How it works:
它的工作原理:
For more information about the PHP Expat functions, visit our PHP XML Parser Reference.
如果你希望了解更多关于PHP Expat函数的信息,请访问我们的PHP XML Parser 参数。