Use PHP to collaborate with XML for Web programming

Source: Internet
Author: User
Tags character set error code object model parse error php file xml parser xpath xsl

First, small sequence

HTML is easy to learn and general, the general PHP program is embedded in the HTML language implementation. But as the web becomes more widely used, the weakness of HTML is becoming more and more obvious. The advent of XML, which compensates for these deficiencies, provides a common way to handle all the data on the Internet.

Second, the limitations of HTML analysis

1, the scalability of HTML is poor. Although HTML should suffice as a general application, the HTML has obvious drawbacks when dealing with symbols such as math and chemistry, and it cannot be extended, which greatly limits its development.

2, link loss can not be automatically corrected. Because the URL address of the Web page often changes, and changes the URL address must manually modify this information, otherwise you will encounter the "404URL address not Found" information, which greatly increased the maintenance of the Web page workload.


3, the data search for a long time. Because HTML is used primarily to control the display of a Web page, the same data has different storage formats in different Web pages, which makes it impossible to quickly find the data when it is searched.

4, HTML for Double-byte or multi-state text support is not enough. For example, the Chinese information page will appear in different platforms can not be displayed and so on.

It is because of these shortcomings that people have studied web page making languages that can replace HTML. These are already in use: Extensible Markup Language XML, cascading style sheets (CSS), and Dynamic HTML (DHTML).

Iii. Composition of XML

Here are a few key XML technologies:

1. DTD (document type Declaration)

The main function of the DTD is to define the content schema of the XML, limit the data range of the XML markup, and define the data type of the property. However, because it is not written in XML, extensibility is poor, and only a limited number of data types are available, so its role is limited.

2. XML Schema

The XML schema works like a DTD. But the difference is that the schema file describes the specific type of elements and attributes in the XML file that references it. In addition, because it is written in XML, schemas and DTDs compare with the following advantages:

· The XML schema content model is open and can be expanded at will, and the DTD cannot parse the expanded content.

· A DTD can only define a content type as a string, whereas an XML schema allows content types to be defined as integers, floating-point types, booleans, or many other simple data types.

· XML Schemas use namespaces to associate a particular node in a document with a schema, an XML file can have multiple schemas, and an XML file can have only one DTD.

3, XLink

As a Web language, the ability to link XML is very important. The linking and addressing mechanisms for XML include XLink, XPath, and XPointer. XLink provides a powerful link method that allows you to establish one-way or multi-directional complex connections between documents, as well as a variety of link functions such as annotation links, profile links, extended link sets, and more. XPath is used in XSLT and xpointer to support positioning relative to nodes and node sets in XML documents. XPointer provides a location for the internal structure of the content of an XML document, such as a string or a selected paragraph, on the basis of XPath. The ability to link XML is greatly enhanced than HTML.

4. CSS and XSL

One of the great features of XML is the separation of content from formatting, which means that the XML document does not contain information about how to display/represent the document. CSS and XSL (XML Style Language) solve the problem of displaying XML documents.

CSS (cascading style sheets) can also be used in HTML and XML. XSL fully uses XML syntax, and functionality is much more powerful than CSS.

5, DOM
The Document Object Model (DOM) is a platform-and language-independent program interface that provides the means to dynamically access and update the content, structure, and style of a document. The text can be treated as further processing and the results of the processing are updated to the presentation page.


The goal of DOM is to define a standard programming interface for XML and HTML, which includes the core, HTML, and XML three parts. The core of the DOM establishes a set of underlying objects that can represent any structured document. HTML and XML provide a high-level interface that can be used as a more convenient document view. The DOM specification consists of objects and methods. Programmers use them to make it easier to access and manipulate specific types of documents.

6, namespaces

Namespaces is a collection of all names that are distinguished by URLs and that appear in the elements and attributes of an XML file. In XML, users can define tags and elements themselves. Therefore, if you combine multiple XML files into one, there is a good chance of conflict. namespaces solved the problem.

Iv. PHP support for XML

PHP provides strong support for XML. It uses an XML "parser" and, in order to support the parser, it provides a parse function of PHP4 XML. Here are some of the most commonly used PHP parsing functions.

1. Xml_parse

Boolean xml_parse (int parser, string data, int [isfinal]);

This function is used to parse file data in XML format. Parameter parser to parse code. The parameter data is a parsed data block (chunk). Parameter isfinal can be omitted, and if set to true the system will automatically send the final data section (piece) to the data parameter. Returns a true value if there are no errors.

2. Xml_parser_create

int Xml_parser_create (string [encoding]);

This function is used to initialize a new XML parser. Parameter encoding can be omitted, the character set used for XML, the default value is Iso-8859-1, and other us-ascii, UTF-8 two kinds. Success returns the parser code for use by other functions, and returns a false value if it fails.

3. Xml_set_element_handler

Boolean xml_set_element_handler (int parser, string startelementhandler, String endelementhandler)

The header for this function configuration element is used by the Xml_parse () function. Parameter parser to parse code. The parameters Startelementhandler and Endelementhandler are the headers for the start and end of the element respectively, where the Startelementhandler must include parsing code, name, and attributes, and Endelementhandler The parameters include the parsing code and the name two parameters. Returns a true value if there are no errors.

4. Xml_set_character_data_handler

Boolean xml_set_character_data_handler (int parser, string handler);


This function configures the headers for character data. Parameter parser to parse code. The parameter handler includes two elements, such as parsing code and data string. Returns a true value if there are no errors.

5. Xml_get_error_code

int Xml_get_error_code (int parser);

This function gets the error code when the XML is being processed. Parameter parser to parse code. Return false value if parser wrong, otherwise return error code (such as Xml_error_binary_entity_ref ...). etc.).

6. xml_error_string

string xml_error_string (int code);

This function gets the error code when the XML is being processed. The parameter code is the parse error codes. If no error returns a literal description string for the code.

7. Xml_get_current_line_number

int xml_get_current_line_number (int parser);

This function is used to get the line number that the current XML parsing is processing. Parameter parser to parse code. If parser error, return the value of false, if no errors are returned line number number.

8. Xml_parser_free

Boolean xml_parser_free (int parser);

This function is used to release the memory used by the current XML parsing. Parameter parser to parse code. Returns a true value if there are no errors, otherwise returns a value of false.

V. Analysis of cases

The following is an example of using the PHP5 implementation to read an address book address.xml written in XML 1.0 format and display its contents. See the notes in detail.

?
//
The first part: several PHP helper functions
//

/*********************************

* Read XML from a file *
* Content to String *

*********************************/

function Read_file ($filename)
{
Reading files
$lines =file ($filename);
Variable $contents is a variable that holds the contents of a file
$contents = "";
while (list ($key, $value) =each ($lines))
{
$contents. = $value;
}
return $contents;
}

/*********************************
* When PHP encounters an XML start tag *
* Call, its function is according to a certain level *
* Show XML tags *
*********************************/

Function start_element ($parser, $name, $attrs)
{
///variable $depth depth of markup
Global $depth;
 Variable $spacer all arrow symbols
$spacer = "" before holding the tag;
 for ($i =1; $i $depth [$parser]; $i + +)
{
$spacer. = "->";
 
//sets the color to display when marking
if ($depth [$parser]==0)
{
$font _color= "Red";
  
Else
if ($depth [$parser]==1)
{
$font _color= "green";
 
Else
{
$font _color= "Blue";
 
//Set the font to display when marking
$font _size=5-$depth [$parser];
 if ($font _size<2)
{
$font _size=2;

//Show Markup
echo " ";
Echo $spacer. $depth [$parser];  
if ($depth [$parser] <> 0
{
echo ",";
The
Echo $name.
";
Echo ;
$depth [$parser]++;  
//If the main tag shows a red horizontal line
if ($depth [$parser]==2)
{
echo

;
}
}

/*********************************
* When PHP encounters an end tag for XML *
* Call, its role is to change the current level *
* Count and show horizontal line under main Mark *
*********************************/

function Stop_element ($parser, $name)
{
Variable $depth The depth of the store tag
Global $depth;
$depth [$parser]--;
If the main tag shows a red horizontal line
if ($depth [$parser]==2)
{
echo "

";
}
}

/*********************************
* When PHP encounters an XML-tagged content
* Call, its function is according to a certain level *
* Show the contents of the tag *
*********************************

function Char_data ($parser, $data)
{
Variable $depth The depth of the store tag
Global $depth;
Display the contents of a tag
$data =trim ($data);
if (strlen ($data))
{
for ($i =1; $i $depth [$parser]+6; $i + +)
echo "&NBSP";
echo " $data
";
}
}

//
Part II: PHP File start Execution Department
//
The name of the XML file to parse

$file = "Address.xml";
Reading files
$data =read_file ($file);

instance of generating parser
$parser = Xml_parser_create ();
Setting up a handler function
Xml_set_element_handler ($parser, "start_element", "stop_element");
Xml_set_character_data_handler ($parser, "char_data");
Parsing files
if (!xml_parse ($parser, $data, 1))
{
Error
Die (sPRintf ("XML error:%s at line%d")
Xml_error_string (Xml_get_error_code ($parser)),
Xml_get_current_line_number ($parser)));
}

Release parser
Xml_parser_free ($parser);
? >

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.