Analysis of various methods for php xml operations (more detailed)

Source: Internet
Author: User

XML is a popular semi-structured file format that stores data in a format similar to a database. In practical applications, some simple and less secure data is often stored in the XML file format. On the one hand, this can improve the reading efficiency by reducing interactive operations with the database, and on the other hand, it can effectively use the advantages of XML to reduce the difficulty of programming.
PHP provides a complete set of methods to read XML files, so you can easily write XML-based scripts. This chapter introduces PHP and XML operations and briefly introduces several common XML class libraries.
1 XML Introduction
XML is the abbreviation of eXtensible Markup Language. It is a Markup Language similar to HTML. However, unlike HTML, XML is mainly used to describe data and store data, while HTML is mainly used to display data.
XML is a "meta tag" language. developers can create tag names based on their own needs. For example, the following XML code can be used to describe a message.

Copy codeThe Code is as follows: <thread>
<Title> Welcome </title>
<Author> Simon </author>
<Content> Welcome to XML guestbook !! </Content>
</Thread>

The <thread> and </thread> labels mark a message. The message contains the title, author, and content, which fully expresses a message.
At the top of an XML file, usually <? Xml version = "1.0"?> To identify the start of XML data and use standard version information for XML data. Access the XML file in the browser and you can see the XML data in a clear hierarchy, as shown in 1.

XML has developed rapidly. In recent years, many software developers have begun to develop applications using XML development standards. In addition, many emerging technologies are structured on XML data. This means that XML will become an indispensable part of Web technology like HTML.
2 simple XML operations
In practical applications, PHP and XML interactive operations are widely used. SimpleXML is a new simplified PHP 5 component.
Compared with traditional XML components, SimpleXML components are easy to use. This section describes how to use
The SimpleXML component provides a detailed description of how to operate XML.
2.1 create a SimpleXML object
SimpleXML objects are temporary variables used to temporarily store XML data. Operations on XML are performed by operating SimpleXML objects. The SimpleXML component provides two methods to create SimpleXML objects. The first method is to use the simplexml_load_string function to read the XML data in a string variable. The syntax format is as follows.
Simplexml_load_string (string data)
The data variable is used to store XML data. The following code creates a SimpleXML object using the simplexml_load_string function:Copy codeThe Code is as follows: <? Php
$ Data = <XML // defines XML data
<? Xml version = '1. 0'?>
<Departs>
<Depart>
<Name> production support </name>
<Employees>
<Employee>
<Serial_no> 100001 </serial_no>
<Name> Simon </name>
<Age> 24 </age>
<Birthday> 1982-11-06 </birthday>
<Salary> 5000.00 </salary>
<Bonus> 1000.00 </bonus>
</Employee>
<Employee>
<Serial_no> 100002 </serial_no>
<Name> elasticity </name>
<Age> 24 </age>
<Birthday> 1982-01-01 </birthday>
<Salary> 6000.00 </salary>
<Bonus> 2000.00 </bonus>
</Employee>
</Employees>
</Depart>
<Depart>
<Name> testing center </name>
<Employees>
<Employee>
<Serial_no> 110001 </serial_no>
<Name> Helen </name>
<Age> 23 </age>
<Birthday> 1983-07-21 </birthday>
<Salary> 5000.00 </salary>
<Bonus> 1000.00 </bonus>
</Employee>
</Employees>
</Depart>
</Departs>
XML;
$ Xml = simplexml_load_string ($ data); // create a SimpleXML object
Print_r ($ xml); // output XML
?>

In the preceding example, the $ data variable stores a piece of XML data. The simplexml_load_string function converts the variable $ data to a SimpleXML object. The output of the print_r function shows the structure of the object. The running result is as follows.Copy codeThe Code is as follows: SimpleXMLElement Object
(
[Depart] => Array
(
[0] => SimpleXMLElement Object
(
[Name] => production support
[Employees] => SimpleXMLElement Object
([Employee] => Array (
[0] => SimpleXMLElement Object
([Serial_no] => 100001)
[Name] => Simon
[Age] => 24
[Birthday] => 1982-11-06
[Salary] = & gt; 5000.00
[Bonus] = & gt; 1000.00
)
[1] => SimpleXMLElement Object
([Serial_no] => 100002)
[Name] => Elasticity
[Age] => 24
[Birthday] => 1982-01-01
[Salary] = & gt; 6000.00
[Bonus] = & gt; 2000.00
)
)
)
)
[1] => SimpleXMLElement Object
(
[Name] => testing center
[Employees] => SimpleXMLElement Object
(
[Employee] => SimpleXMLElement Object
(
[Serial_no] = & gt; 110001
[Name] => Helen
[Age] => 23
[Birthday] => 1983-07-21
[Salary] = & gt; 5000.00
[Bonus] = & gt; 1000.00
)
)
)
)
)

The output shows that the structure of SimpleXML object is exactly the same as that of XML data.
The second method is to use the simplexml_load_flie function to read an XML file and create the file. The syntax format is as follows.
Simplexml_load_file (string filename)
The filename variable is the file name and path used to store the XML data file. The following code uses the simplexml_load_file function to create a SimpleXML object.Copy codeThe Code is as follows: <? Php
$ Xml = simplexml_load_file ('example. xml'); // create a SimpleXML object
Print_r ($ xml); // output XML
?>

Among them, the data stored in example. xml is exactly the same as the above $ data, and the running result is also the same as above.
The above two methods implement the same function, the difference is that the XML data source is different. If the XML data source is in the PHP script file, use simplexml_load_string to create it. If the XML data source is in a separate XML file, you must use simplexml_load_file to create it.
2.2 read XML data from SimpleXML objects
The previous section describes how to use the print_r function to read data from SimpleXML objects. The returned results are similar to the structure of arrays. Obviously, this display method is not desirable in practical applications. Here we will introduce several other methods to read XML data from SimpleXML objects.
1. The var_dump function displays the object details.
The var_dump function can be used to display the detailed information of SimpleXML objects. Compared with the print_r function, the var_dump function displays more complete information. Its syntax is as follows.
Void var_dump (object1, object2... )
The following code uses the var_dump function to output the object details in the preceding example.Copy codeThe Code is as follows: <? Php $ xml = simplexml_load_file ('example. xml'); // create SimpleXML object var_dump ($ xml); // output xml?>

The running result is as follows.Copy codeThe Code is as follows: object (SimpleXMLElement) #1 (1) {["depart"] => array (2 ){
[0] =>
Object (SimpleXMLElement) #2 (2 ){
["Name"] =>
String (18) "production support"
["Employees"] =>
Object (SimpleXMLElement) #4 (1 ){
["Employee"] =>
Array (2 ){
[0] =>
Object (SimpleXMLElement) #5 (6 ){
["Serial_no"] =>
String (6) 100001 ″
["Name"] =>
String (5) "Simon"
["Age"] =>
String (2) "24 ″
["Birthday"] =>
String (10) "1982-11-06 ″
["Salary"] =>
String (7) 5000.00 ″
["Bonus"] =>
String (7) 1000.00 ″
}
[1] =>
Object (SimpleXMLElement) #6 (6 ){
["Serial_no"] =>
String (6) 100002 ″
["Name"] =>
String (6) "Elaine"
["Age"] =>
String (2) "24 ″
["Birthday"] =>
String (10) "1982-01-01 ″
["Salary"] =>
String (7) 6000.00 ″
["Bonus"] =>
String (7) 2000.00 ″
}
}
}
}
[1] =>
Object (SimpleXMLElement) #3 (2 ){
["Name"] =>
String (14) "testing center"
["Employees"] =>
Object (SimpleXMLElement) #7 (1 ){
["Employee"] =>
Object (SimpleXMLElement) #8 (6 ){
["Serial_no"] =>
String (6) 110001 ″
["Name"] =>
String (5) "Helen"
["Age"] =>
String (2) "23 ″
["Birthday"] =>
String (10) "1983-07-21 ″
["Salary"] =>
String (7) 5000.00 ″
["Bonus"] =>
String (7) 1000.00 ″
}}}}}

Compared with the result output by print_r, the output result structure of the var_dump function is more rigorous, and the Data Types of each attribute in the object are analyzed. In practical applications, the var_dump function is often used for object detection during program debugging.
2. Read tags from XML data
Similar to operating on Array variables, reading XML can also be done in a similar way. For example, to read the "name" attribute under each "depart" label in the preceding XML data, you can use the foreach function, as shown in the following code:
.Copy codeThe Code is as follows: <? Php $ xml = simplexml_load_file ('example. xml'); foreach ($ xml-> depart as $)
{
Echo "$ a-> name <BR> ";
}
?>

The running result is as follows.
Production support
Testing center
// Read the XML file // read every depart tag in XML data cyclically
// Output the name attribute
You can also use square brackets ([]) to directly read tags specified in XML data. The following code outputs the "name" attribute of the first "depart" tag in the preceding XML data.Copy codeThe Code is as follows: <? Php
$ Xml = simplexml_load_file ('example. xml'); // read the xml file
Echo $ xml-> depart-> name [0]; // output Node
?>

The running result is as follows.
Production support
The SimpleXML component provides the children Method for reading all sub-tags under a tag. For example, the "depart" label in the XML data above contains two sub-tags: "name" and "employees ". The following code reads sub-tags under the first "depart" tag.Copy codeThe Code is as follows: <? Php
$ Xml = simplexml_load_file ('example. xml ');
Foreach ($ xml-> depart-> children () as $ depart) // read sub-tags under the depart tag cyclically
{
Var_dump ($ depart); // output the XML data of the tag
}
?>

The running result is as follows.Copy codeThe Code is as follows: object (SimpleXMLElement) #3 (1 ){
[0] =>
String (18) "production support"
}
Object (SimpleXMLElement) #5 (1 ){
["Employee"] =>
Array (2 ){
[0] =>
Object (SimpleXMLElement) #3 (6 ){
["Serial_no"] =>
String (6) 100001 ″
["Name"] =>
String (5) "Simon"
["Age"] =>
String (2) "24 ″
["Birthday"] =>
String (10) "1982-11-06 ″
["Salary"] =>
String (7) 5000.00 ″
["Bonus"] =>
String (7) 1000.00 ″
}
[1] =>
Object (SimpleXMLElement) #6 (6 ){
["Serial_no"] =>
String (6) 100002 ″
["Name"] =>
String (6) "Elaine"
["Age"] =>
String (2) "24 ″
["Birthday"] =>
String (10) "1982-01-01 ″
["Salary"] =>
String (7) 6000.00 ″
["Bonus"] =>
String (7) 2000.00 ″
}
}
}

We can see that after the children method is used, all sub-labels are processed as a New XML file.
3. Query Based on XML data path
The SimpleXML component provides a query method based on the XML data path. The XML data path is all the labels that pass through from the XML root to a tag. This path uses the slash "/" to separate tag names. For example, for the preceding XML data, to query the values in the "name" of all tags, the path from the root to the departs, depart, employees, and employee tags
"/Departs/depart/employees/employee/name ". The SimpleXML component uses the xpath method to parse the path. The syntax format is as follows.
Xpath (string path)
The path is the path. This method returns an array containing all the tag values to be queried. The following code queries all the name tags in the preceding XML data.Copy codeThe Code is as follows: <? Php
$ Xml = simplexml_load_file ('example. xml'); // read the xml file
$ Result = $ xml-> xpath ('/departs/depart/employees/employee/name'); // define a node
Var_dump ($ result); // output Node
?>

The running result is as follows.Copy codeThe Code is as follows: array (3 ){
[0] => object (SimpleXMLElement) #2 (1 ){
[0] => string (5) "Simon"
}
[1] => object (SimpleXMLElement) #3 (1 ){
[0] => string (6) "elasticity"
}
[2] => object (SimpleXMLElement) #4 (1 ){
[0] => string (5) "Helen"
}
}

We can see that all the name tags are queried.
2.3 XML data modification
The method for modifying XML data is similar to that for reading labels in XML data. That is, you can directly modify the label value in the SimpleXML object. The following code modifies the "name" sub-tag of the first "depart" tag in the preceding XML data.Copy codeThe Code is as follows: <? Php
$ Xml = simplexml_load_file ('example. xml'); // read xml
$ Xml-> depart-> name [0] = "Human Resource"; // modify a node
?>

After modification, it does not affect the XML file. However, in a program, read SimpleXML objects using modified values.
2.4 standardized XML data
SimpleXML also provides an asXML Method for standardizing XML data. The asXML method can effectively orchestrate content in SimpleXML objects according to the XML 1.0 standard and return the Data Type of strings. The following Code standardizes the preceding XML data.Copy codeThe Code is as follows: <? Php
$ Xml = simplexml_load_file ('example. xml'); // read xml data
Echo $ xml-> asXML (); // standardize XML data
?>

2.5 storage of XML data
It is very easy to store XML data in SimpleXML objects to an XML file. You can simply output the returned results of the asXML method to a file. The following code first modifies the depart name in the XML file, and then outputs the modified XML data to another XML file.Copy codeThe Code is as follows: <? Php
$ Xml = simplexml_load_file ('example. xml'); // read xml data
$ Newxml = $ xml-> asXML (); // standardize XML data
$ Fp = fopen ("newxml. xml", "w"); // open the file to write XML data
Fwrite ($ fp, $ newxml); // write XML data
Fclose ($ fp); // close the file
?>

After the code is run, you can see the xml data in the newxml. XML file as follows.
We can see that the modifications to the XML file have been saved to the output file.
3. Dynamic Creation of XML documents
In practical applications, you may need to dynamically generate XML documents. The SimpleXML component described earlier does not provide methods for creating XML documents. Therefore, if you need to dynamically create XML documents, you can use the DOM component to create them. DOM is the abbreviation of Document Object Model. The DOM component provides a tree-based resolution mode for XML documents. The following code creates an XML document using the DOM component.

Copy codeThe Code is as follows: <? Php
// Create a new DOM document
$ Dom = new DomDocument ();
// Create a departs tag on the Root Node
$ Departs = $ dom-> createElement ('demopart ');
$ Dom-> appendChild ($ departs );
// Create a depart subtag under the departs tag
$ Depart = $ dom-> createElement ('Demo ');
$ Departs-> appendChild ($ depart );
// Create an employees sub-tag under the depart tag
$ Employees = $ dom-> createElement ('ployees ');
$ Depart-> appendChild ($ employees );
// Create the employee subtag under the employees tag
$ Employee = $ dom-> createElement ('Employee ');
$ Employees-> appendChild ($ employee );
// Create the serial_no sub-tag under the employee tag
$ Serial_no = $ dom-> createElement ('serial _ no ');
$ Employee-> appendChild ($ serial_no );
// Add Value node 100001 for the serial_no label
$ Serial_no_value = $ dom-> createTextNode ('000000 ′);
$ Serial_no-> appendChild ($ serial_no_value );
// Output XML data
Echo $ dom-> saveXML ();
?>
The output result is as follows.
<? Xml version = "1.0"?>
<Departs>
<Depart>
<Employees>
<Employee>
<Serial_no> 100001 </serial_no>
</Employee>
</Employees>
</Depart>
</Departs>

In addition to dynamically creating XML documents, the DOM component can also be used to read XML files. The following code implements
XML file reading.Copy codeThe Code is as follows: <? Php
$ Dom = new DomDocument (); // create a DOM object
$ Dom-> load ('example. xml'); // read the xml file
$ Root = $ dom-> documentElement; // get the root of XML data
Read_child ($ root); // call the read_child function to read the root object
Function read_child ($ node)
{
$ Children = $ node-> childNodes; // obtain all child nodes of $ node
Foreach ($ children as $ e) // read each subnode cyclically
{
If ($ e-> nodeType = XML_TEXT_NODE) // if the child node is text, the output
{
Echo $ e-> nodeValue. "<BR> ";
}
Else if ($ e-> nodeType = XML_ELEMENT_NODE) // if the child node is a Node object, call the function for processing.
{
Read_child ($ e );
}
}
}
?>

The running result is as follows.Copy codeThe Code is as follows: Reference
Production support
100001
Simon
24
1982-11-06
5000.00
1000.00
100002
Eline
24
1982-01-01
6000.00
2000.00
Testing center
110001
Helen
23
1983-07-21
5000.00
1000.00

In the preceding example, XML data is processed recursively, and all text tags in XML data are output.
4. XML application instance-message book
This section describes the basic XML operations. This section describes how to implement the interaction between PHP and XML data in actual applications by designing an XML message book.
4.1 XML file structure design
The XML file is used to store XML data, that is, messages in the message book. Here, for each message, XML data mainly includes three items: the message title, the name of the message owner, and the message content. Therefore, the XML file format is designed as follows.

Copy codeThe Code is as follows: <? Xml version = "1.0"?>
<Threads>
<Thread>
<Title> here is the title of the message </title>
<Author> here is the message recipient </author>
<Content> here is the message content </content>
</Thread>
</Threads>

4.2 compile the submission page
The submit message page consists of two pages. One is the HTML file used by the visitor to write the form of the message, and the other is the PHP script used to process the visitor's input. The HTML code of the form is as follows.Copy codeThe Code is as follows: <Head>
<Title> post a new message </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
</Head>
<Body>
<H1> <p align = "center"> post new messages </p> </H1>
<Form name = "form1" method = "post" action = "Post. php">
<Table width = "500" border = "0" align = "center" cellpadding = "0" cellspacing = "0">
<Tr>
<Td> title </td>
<Td> <input name = "title" type = "text" id = "title" size = "50"> </td>
</Tr>
<Tr>
<Td> author </td>
<Td> <input name = "author" type = "text" id = "author" size = "20"> </td>
</Tr>
<Tr>
<Td> content </td>
<Td> <textarea name = "content" cols = "50" rows = "10" id = "content"> </textarea> </td>
</Tr>
</Table>
<P align = "center">
<Input type = "submit" value = "Submit">
<Input type = "reset" value = "Reset">
</P>
</Form>
</Body>
</Html>

For PHP scripts used to process user input, the basic logic is to first create a DOM object and then read the XML data in the XML file, next, create a node on the XML object, store the user input, and output the XML data to the original XML file. The specific implementation code is as follows.Copy codeThe Code is as follows: <? Php
$ Guestbook = new DomDocument (); // create a new DOM object
$ Guestbook-> load ('db/guestbook. xml'); // read xml data
$ Threads = $ guestbook-> documentElement; // obtain the root of the XML structure
// Create a new thread Node
$ Thread = $ guestbook-> createElement ('thread ');
$ Threads-> appendChild ($ thread );
// Create the title tag on the new thread Node
$ Title = $ guestbook-> createElement ('title ');
$ Title-> appendChild ($ guestbook-> createTextNode ($ _ POST ['title']);
$ Thread-> appendChild ($ title );
// Create the author label on the new thread Node
$ Author = $ guestbook-> createElement ('author ');
$ Author-> appendChild ($ guestbook-> createTextNode ($ _ POST ['author']);
$ Thread-> appendChild ($ author );
// Create the content tag on the new thread Node
$ Content = $ guestbook-> createElement ('content ');
$ Content-> appendChild ($ guestbook-> createTextNode ($ _ POST ['content']);
$ Thread-> appendChild ($ content );
// Write XML data to a file
$ Fp = fopen ("DB/guestbook. xml", "w ");
If (fwrite ($ fp, $ guestbook-> saveXML ()))
Echo "message submitted successfully ";
Else
Echo "Message submission failed ";
Fclose ($ fp );
?>

Run the preceding HTML file in the browser and enter the appropriate message content, as shown in figure 2.

Figure 2 new message posting page
Click Submit. The content in the XML file is as follows.
You can see that the message is stored in the XML file.
4.3 compile the display page
The display page can be easily implemented using the SimpleXML component described earlier. The specific implementation code is as follows.Copy codeThe Code is as follows: <? Php
// Open the XML file used to store messages
$ Guestbook = simplexml_load_file ('db/guestbook. xml ');
Foreach ($ guestbook-> thread as $ th) // read every thread tag in XML data cyclically
{
Echo "<B> title: </B>". $ th-> title. "<BR> ";
Echo "<B> author: </B>". $ th-> author. "<BR> ";
Echo "<B> content: </B> <PRE>". $ th-> content. "</PRE> ";
Echo "<HR> ";
}
?>

View the running result 3 in the browser.

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.