XML Application in PHP

Source: Internet
Author: User
Tags cdata command line count mysql php and trim xml example xml parser
A summary of 

xml represents the abbreviation for Extensible Markup Language (extensible Markup, meaning Extensible Markup Language). XML is a set of rules that define semantic markup that divides documents into many parts and identifies them. It is also a Meta markup language, defined as a syntactic language for defining other semantic, structured markup languages related to a particular domain. XML is the hottest technology today. and PHP also has the ability to analyze XML documents, we will discuss the application of XML in PHP together.

xml Overview

Talking about XML (eXtended Markup Language: Extensible Markup Language), let's look at a piece of HTML code first:

£
XML
£
£

text



£
£

The above code is structurally compliant with the XML rules, and XML can be understood to be a tree-like structure type that contains data:

1, referencing the same element, using consistent capitalization, such as

, is not compliant
2, any property values (such as href= "????") To be caused by "", such as is incorrect.
3, all elements must consist of open and close callouts, elements should be shaped like or empty element , if the end of the "/>" less "/" is the wrong code
4, all elements must be nested with each other, just like the loop of writing a program, and all elements must be nested within the root element, such as the above code, where all content is nested within .
5, the element name (that is, the body a P IMG, etc.) should begin with a letter.

How to apply PHP XML parser expat?

expat is an XML parser (also known as an XML processor) in the PHP scripting language that enables programs to access the structure and content of XML documents. It is an event-based parser. There are two basic types of XML parsers:

A tree-based parser: Converts an XML document into a tree-like structure. This type of parser analyzes the entire article and provides an API to access each element of the resulting tree. Its common 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 will invoke the function provided by the developer to handle it. An event-based parser has a view of the dataset in an XML document, which means it is concentrated in the data portion of the XML document, not its structure. These parsers process the document from start to finish and report to the application similar to the beginning of the element, the end of the element, the beginning of the feature data, and so on-events through the callback (callback) function.

The following is an example of an "Hello-world" XML document:


Hello World

The event-based parser will report as three events:

Start element: Greeting
The beginning of the cdata entry, the value is: Hello World
End element: Greeting

An event-based parser does not produce a structure that describes the document, and of course if you use expat, it can generate a complete native tree structure in PHP as necessary. In a CDATA item, an event-based parser does not get information about the greeting of the parent element. However, it provides a lower level of access, which makes it possible to make better use of resources and faster access. In this way, there is no need to put the entire document into memory, and in fact the entire document can even be larger than the actual memory value.

The example above Hello-world includes the full XML format, but it is not valid because there is neither a DTD (document type definition) associated with it nor an inline DTD. However, expat is a parser that does not check for validity, and therefore ignores any DTD associated with the document. It should be noted that the document still needs the full format, otherwise expat (like any other XML-compliant parser) will stop with the error message.

Compile expat

Expat can be compiled into the PHP3.0.6 version (or more). Starting with Apache1.3.22, expat has been part of Apache. In UNIX systems, you can configure PHP to compile it into PHP using the-with-xml option.

If you compile PHP as an Apache module, expat will default as part of Apache. In Windows, you must load the XML dynamic connection library.

XML Example: Xmlstats
The example we are going to discuss is using expat to collect statistics for XML documents.

For each element in the document, the following information is output:
The number of times the element is used in the document
The number of character data in the element

Element's parent element

Child elements of an element
Note: In order to demonstrate, we use PHP to create a structure to hold the parent element and child element of the element


What are the functions that  uses to produce an instance of an XML parser?

The function used to produce an instance of an XML parser is xml_parser_create (). The instance will be used for all future functions. This idea is very similar to the connection mark of MySQL function in PHP. An event-based parser typically requires a registration callback function before parsing a document-for a particular event to occur. Expat no exceptions, it defines the following seven possible events:

Object XML parsing function description
Start and end of 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 entity xml_set_unparsed_entity_decl_handler () unresolved external entities appear
Processing instruction Xml_set_processing_instruction_handler () the appearance of processing instructions
The appearance of the Declaration of Xml_set_notation_decl_handler () notation of notation
Default Xml_set_default_handler () other events that do not have a handler function specified

All callback functions must have an instance of the parser as its first argument (in addition to other parameters).

For the example script at the end of this article, it is necessary to note that it uses both the element processing function and the character data processing function. The callback handler function for the element is registered by Xml_set_element_handler ().

This function requires three parameters:

Example of the parser
Name of the callback function that handles the start element
Name of the callback function that handles the end element

When you begin parsing an XML document, the callback function must exist. They must be defined as consistent with the prototype described in the PHP manual.

For example, expat passes three arguments to the handler function of the start element. In the scripting example, it is defined as follows:

function start_element ($parser, $name, $attrs)

$parser is the parser flag, $name is the name of the start element, $attrs is an array containing all the attributes and values of the element.

Once the XML document is parsed, expat will invoke the Start_element () function and pass the arguments to the previous element when it encounters the start elements.

Case folding options FOR XML

Close the case folding option with the Xml_parser_set_option () function. This option is turned on by default, so that the element name passed to the handler is automatically converted to uppercase. However, XML is sensitive to capitalization (so capitalization is very important for statistical XML documents). For our example, the case folding option must be closed.

How do I parse a document?

Now that the script can finally parse the XML document after all the preparations have been done:

xml_parse_from_file (), a custom function that opens the file specified in the parameter and resolves it in 4kb size
Xml_parse (), like the Xml_parse_from_file (), returns False when an error occurs that the XML document is not in full format.

We can use the Xml_get_error_code () function to get the last error of the numeric code. Pass this digital 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.

When parsing a document, the question for expat needs to be emphasized: how do you keep a basic description of the document structure?

As mentioned earlier, the event-based parser itself does not produce any structural information. However, the tag structure is an important feature of XML. For example, the element sequence represents a different meaning than

. The title and the name of the picture are not related, although they all use the term "title". Therefore, in order to use an event-based parser to process XML more effectively, you must use your own stack (stacks) or list (lists) to maintain the document's structural information.</p>

To produce a mirror image of the document structure, the script needs to know at least the parent element of the current element. The EXAPT API is not implemented, and it reports only the events of the current element, without any information about the relationship. Therefore, you need to build your own stack structure.

The script example uses the advanced back-out (FILO) stack structure. With an array, the stack saves all the start elements. For the start element handler function, the current element will be pushed to the top of the stack by the Array_push () function. Accordingly, the end element handler function removes the topmost element by Array_pop ().

For the sequence , the stack is populated as follows:

Start element Book: assigns "book" to the first element of the stack ($stack [0]).
Start element title: Assign "title" to the top of the stack ($stack [1]).
The end element title: Removes the topmost element from the stack ($stack [1]).
The end element title: Removes the topmost element from the stack ($stack [0]).

PHP3.0 The example by manually controlling the nesting of elements with a $depth variable, which makes the script look more complex. PHP4.0 makes the script look more concise by Array_pop () and Array_push () two functions.

How do I collect the element information in an XML document?

To gather information about 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 properties (variables of the class)

$count-Number of times the element was found in the document
$chars-Number of bytes of character event in element
$parents-Parent Element
$childs-child elements

Note: One feature of PHP is that you can traverse the entire class structure through the while (list () = each ()) loop as you traverse the entire corresponding array. All class variables (when you use PHP3.0 and method names) are output as strings.

When an element is found, we need to increment its corresponding register to track how many times it appears in the document. Add one to the count element in the corresponding $elements item.

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 current element should remember who is its parent element. Therefore, the parent element is added to the project of the current element $parents array.

Show statistic Information

The rest of the code loops through the $elements array and its child arrays to show its statistical results. This is the simplest nested loop, although the output is the correct result, but the code is neither concise nor any particular technique, it is just a loop that you may use to complete the work every day.


The scripting example is designed to be invoked through the command line in PHP's CGI mode. Therefore, the format of the statistical results output is text format. If you want to apply the script to the Internet, you need to modify the output function to produce HTML format.

How to use Php&xml to compile a mini search engine example?

Let's first familiarize ourselves with the XML (saved as Xyz.xml) that is used in our program.

a search engine built with PHP and XML technology
name1
Computer Network
name2
programming
name3
PHP
http://www.phpbuilder.com/memo=" [English]php development resources. ">
Www.phpbuilder.com
http://www.fokus.gmd.de" memo= "[English]php Development Manual. ">
PHP Manual



Its structure is quite simple, the root element is links,sub represents a category, the Web is a Web site information, which contains attributes, URL represents the site's join, memo for memo information, ?? , ?? The data that is contained in the is the category and the name of the Web site, which complies with the above rules.

Now let's answer the question raised above: Why use XML to compile search engines?
The first reason is that sometimes we may not be able to use the database (MySQL or other) for a variety of reasons;
Second, for small data search engine, its data volume is very small, if the database to do, the efficiency may not be how high;

The most important point is that the search engine is fairly simple to maintain and does not have to write cumbersome database maintenance programs. For example, we want to add a category or Web page, just edit the text of the file, plus a blessing 紈 eb>??? or ???? on it, and if you want to move a category to another place, we just have to copy this part of the sub to the past.

Below is one of the simplest examples of XML that is shown in PHP.

The following procedure is to parse the XML and output it to the browser according to the tree structure and display the total number of elements per layer.

$file = "Demo.xml";//XML file
function Xml_parse_from_file ($parser, $file) {//parse XML file functions}
function Start_element ($parser, $name, $attrs) {//encountered an open element tag such as function Stop_element ($parser, $name) {//encountered an open element tag such as execute this section}
function data ($parser, $data) {...}
function Showcount () {//Show the total number of elements per layer}

Global $level, $levelcount, $maxlevel;
$level =-1;
$parser = Xml_parser_create ();//Generate Parser instance
Xml_set_element_handler ($parser, "start_element", "stop_element"); Setting up a handler function
Xml_set_character_data_handler ($parser, "data");
Xml_parser_set_option ($parser, xml_option_case_folding, 0);
$ret = Xml_parse_from_file ($parser, $file); Parsing files
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); Release parser
Showcount ();
? >

On the basis of the above program, we can show a section of the subtree, and we will locate it according to the layer of the element and the number of the layer he is on.

For example:

links (0,1)
+----Web (1,1)
+----Sub (1,2)
| +----web (2,1)
| +----SUB (2,2)
| | +----web (3,1)
| | +----SUB (3,2)
:
:
:

The following code is the basis of our search engine. Because, to display a subcategory (such as programming->php->) information will use him.

......
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) {//judge whether within the scope of the subtree, $hide ==false for the
if ($level = = $lev && $levelcount [$level]== $num)
$hide =false;
}else{
if ($level <= $lev) $hide =true;
}

if (! $hide) {
...//output
}
}
function data ($parser, $data) {
Global $level, $hide;
if (! $hide) {
if (Trim ($data)!= "") {echo trim ($data);}
}
}
......
Global $hide, $lev, $num, $PHP _self;
$level =-1;
$hide = TRUE;
echo "

root

";
if ($lev = = "") {
$lev =0; $num = 1;
}
......
? >

mini search engine in the end how to do it?

made a number of bedding, let's take a look at our search engine's main document.

The first paragraph is imitation sina,yahoo query by category
The second paragraph displays the contents of the Search Query section (traversing the entire tree).

xml3.php

Keyword matching using the Eregi function, we assume that the input text will not lead to errors.



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.