PHP XML parsing function code 1th/2 page _php Tutorial

Source: Internet
Author: User
Tags cdata processing instruction xml example xml parser
First I have to admit that I like computer standards. If everyone complies with the standards of the industry, the Internet will be a better medium. The use of standardized data interchange formats enables an open and platform-independent computing model to be practical. That's why I'm a fan of XML.
Fortunately, my favorite scripting language supports XML and is constantly strengthening its support. PHP allows me to quickly publish XML documents to the Internet, collect statistical information from XML documents, and convert XML documents to other formats. For example, I often use PHP's XML processing power to manage the articles and books I write in XML.
In this article, I'll discuss any expat parser built into PHP to work with XML documents. Using the example, I will demonstrate how the expat is handled. At the same time, examples can tell you
How is it:
Build your own processing function
Convert an XML document to your own PHP data structure
Introduction Expat
An XML parser, also known as an XML processor, enables a program to access the structure and content of an XML document. Expat is the XML parser for the PHP scripting language. It is also used in
Other projects, such as Mozilla, Apache, and Perl.
What is an event-based parser?
There are two basic types of XML parsers:
Tree-based parser: Converts an XML document into a tree structure. Such parsers parse the entire article and provide an API to access each element of the resulting tree. Its pass
The standard is DOM (Document object mode).
Event-based parser: treats an XML document as a series of events. When a particular event occurs, the parser invokes the function provided by the developer to process it.
The event-based parser has a data-set view of an XML document, which means it concentrates on the data part of the XML document, not its structure. These parsers from beginning to end
Processes the document and will resemble the start of the element, the end of the element, the start of the feature data, and so on-the event is reported to the application through the callback (callback) function. To
Below is an example of an "Hello-world" XML document:

Hello World

The event-based parser is reported as three events:
Start element: Greeting
CDATA The start of the entry with the value: Hello World
End element: Greeting
Unlike a tree-based parser, event-based parsers do not produce a structure that describes the document. In a CDATA item, the event-based parser does not let you get the parent element
Greeting's information.
However, it provides a lower level of access, which makes it possible to make better use of resources and faster access. In this way, it is not necessary to put the entire document into memory
, and in fact, the entire document can even be larger than the actual memory value.
Expat is a kind of event-based parser. Of course, if you use expat, it can generate a full native tree structure in PHP as necessary.
Examples of the above Hello-world include the full XML format. However, it is not valid because there is no DTD (document type definition) associated with it, and there is no inline DTD.
For expat, this makes no difference: Expat is a parser that does not check for validity, and therefore ignores any DTD associated with the document. However, it should be noted that the document still needs to be completed
Expat (as with other XML-compliant parsers) will stop with the error message.
As a parser that does not check validity, the exapt and lightness of the device make it ideal for Internet applications.
Compiling expat
Expat can be compiled into the PHP3.0.6 version (or above). From Apache1.3.9 onwards, expat has been part of Apache. In Unix systems, the-with
The-xml option configures PHP, which you can compile into PHP.
If you compile PHP as an Apache module, expat will default as part of Apache. In Windows, you have to load the XML dynamic connection library.
XML Example: Xmlstats
One way to understand the functions of expat is through examples. The example we are going to discuss is using expat to collect statistical data for XML documents.
For each element in the document, the following information is output:
The number of times the element was used in the document
The number of character data in the element
The parent element of the element
Element's child element
Note: To demonstrate, we use PHP to generate a structure to hold the elements ' parent and child elements
Get ready
The function used to produce an XML parser instance is Xml_parser_create (). The instance will be used for all future functions. This idea is very similar to the MySQL function in PHP
The connection token. Before parsing a document, an event-based parser typically requires you to register a callback function-called when a particular event occurs. Expat there is no exception to the event, it
The following seven possible events are defined:
Object XML parsing function description
The start and end of the element Xml_set_element_handler () element
Start of character data Xml_set_character_data_handler () character data
External entity Xml_set_external_entity_ref_handler () external entity appears
unresolved external entities xml_set_unparsed_entity_decl_handler () unresolved external entities appear
Processing instruction Xml_set_processing_instruction_handler () the appearance of processing instructions
Notation Statement Xml_set_notation_decl_handler () The appearance of the notation statement
Default Xml_set_default_handler () other events that do not specify a handler function
All callback functions must have an instance of the parser as their first parameter (plus other parameters).
For the sample script at the end of this article. You need to be aware that it uses both the element handler function and the character data processing function. The callback handler for the element is passed
Xml_set_element_handler () to register.
This function requires three parameters:
Examples of parsers
The name of the callback function that handles the start element
The name of the callback function that handles the end element
The callback function must be present when parsing the XML document begins. They must be defined as consistent with the prototypes described in the PHP manual.
For example, expat passes three parameters to the handler function for the start element. In the script example, it is defined as follows:
function Start_element ($parser, $name, $attrs)
The first argument is the parser flag, the second argument is the name of the start element, and the third parameter is an array containing all the attributes and values of the element.
Once you start parsing the XML document, expat will call your start_element () function and pass the arguments past when it encounters the start element.
Case folding option FOR XML
Use the Xml_parser_set_option () function to close the case folding option. This option is turned on by default so that the element name passed to the handler function is automatically converted to
Capital. However, XML is sensitive to capitalization (so the case is very important for statistical XML documents). For our example, the case folding option must be closed.
Parsing documents
After all the preparations have been completed, the script can now parse the XML document:
Xml_parse_from_file (), a custom function that opens the file specified in the parameter and resolves it in 4kb size
Xml_parse (), like Xml_parse_from_file (), returns False when an error occurs, that is, if the XML document is not fully formed.
You can use the Xml_get_error_code () function to get the number code of the last error. Pass this numeric code to the Xml_error_string () function to get
The wrong text message.
Outputs the current number of rows in the XML, making debugging easier.
In the process of parsing, call the callback function.
Describe the document structure
When parsing a document, the question to expat needs to be emphasized: how to maintain a basic description of the document structure?
As mentioned earlier, the event-based parser itself does not produce any structural information.
The tag structure, however, is an important feature of XML. For example, the sequence of elements The meaning of the expression differs from the < figure><title>. In other words, any <BR> will tell you that the title is not related to the map name, although they all use the term "title". Therefore, in order to use the event-based parser more efficiently for XML <BR>, you must use your own stack (stacks) or list (lists) to maintain the structure information of the document. <BR> to create a mirror image of the document structure, the script needs to know at least the parent element of the current element. Using the EXAPT API is not possible, it only reports the current element of the event, and no <BR> has any information about the relationship. Therefore, you need to build your own stack structure. The <BR> script paradigm uses the advanced post-out (FILO) stack structure. With an array, the stack will hold all the start elements. For the start element handler function, the current element will be pushed to the top of the stack by the <br>array_push () function. Accordingly, the end element handler removes the topmost element by Array_pop (). <BR> for sequences <book><title> , the stack is populated as follows:
Start element Book: assigns "book" to the first element of the stack ($stack [0]).
Start element title: assigns "title" to the top of the stack ($stack [1]).
End element Title: Removes the topmost element from the stack ($stack [1]).
End element Title: Removes the topmost element from the stack ($stack [0]).
PHP3.0 implements an example by manually controlling the nesting of elements with a $depth variable. This makes the script look more complex. PHP4.0 through Array_pop () and
Array_push () Two functions to make the script look more concise.
Collect Data
To gather information for each element, the script needs to remember the events for each element. Save all the different elements in the document by using a global array variable $elements
。 An array of items is an instance of an element class, with 4 attributes (variables of the class)
$count-the number of times the element was found in the document
$chars-Number of bytes in a character event in an element
$parents-Parent Element
$childs-child elements
As you can see, it's easy to save class instances in an array.
Note: One of the features of PHP is that you can traverse the entire class structure through the while (list () = every ()) loop as if you were traversing the entire corresponding array. All the classes change
The amount (when you use PHP3.0 and the method name) is output as a string.
When an element is found, we need to add its corresponding register to track how many times it appears in the document. The count element in the corresponding $elements item is also added.
We also want the parent element to know that the current element is its child element. Therefore, the name of the current element will be added to the project of the parent element's $childs array. Finally, the project
The former element should remember who is its parent element. Therefore, the parent element is added to the current element $parents array of items.
To display statistical information
The remainder of the code loops through the $elements array and its sub-arrays to display its statistical results. This is the simplest nested loop, although the correct result is output, but the code is neither simplified
Clean without any special skill, it is just a cycle that you may use to complete the work every day.
The script paradigm is designed to be invoked via the command line of the CGI method of PHP. Therefore, the output of the statistical results is in text format. If you're going to use the script on the Internet,
, then you need to modify the output function to produce HTML formatting.
Summarize
EXAPT is the XML parser for PHP. As an event-based parser, it does not produce a document's structure description. But by providing the underlying access, this makes it possible to make better use of the capital
Source and faster access.
As a parser that does not check for validity, expat ignores the DTD that joins the XML document, but if the document is not in a complete format, it will stop with the error message.
Provides event handlers to work with documents
Build your own event structures such as stacks and trees to get the benefits of XML structure information tagging.
New XML programs appear every day, and PHP support for XML is increasing (for example, adding support for DOM-based XML parser libxml).
With PHP and expat, you can prepare for the upcoming effective, open, and platform-independent standards.

http://www.bkjia.com/PHPjc/319455.html www.bkjia.com true http://www.bkjia.com/PHPjc/319455.html techarticle first I have to admit that I like computer standards. If everyone complies with the standards of the industry, the Internet will be a better medium. Use a standardized data interchange format to make open ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.