Various methods for php xml operations (more detailed) _ PHP Tutorial

Source: Internet
Author: User
Various methods for PHPXML operations (more detailed ). 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 often uses XML files as a popular semi-structured file format, storing 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.

The code is as follows:



Welcome
Simon
Welcome to XML guestbook !!


Where, And The tag indicates a message. The message contains the title, author, and content, which fully expresses a message.
At the top of an XML file 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.
'20180101') this. width = '20180101'; if (this. offsetHeight> '20180101') this. height = '20180101'; "border = 0>
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:

The code is as follows:


$ Data = <


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




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.

The 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.

The code is as follows:


$ 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.

The code is as follows:




The running result is as follows.

The 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:
.

The code is as follows:


Depart as $)
{
Echo "$ a-> name
";
}
?>


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.

The code is as follows:


$ 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.

The code is as follows:


$ 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.

The 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.

The code is as follows:


$ 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.

The 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.

The code is as follows:


$ 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.

The code is as follows:


$ 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.

The code is as follows:


$ 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.

The code is as follows:


// 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.





100001





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.

The code is as follows:


$ 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 ."
";
}
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.

The 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.

The code is as follows:





Here is the message title
Here is the message recipient
Here is the message content



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.

The code is as follows:




Post new messages



Post new messages






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.

The code is as follows:


$ 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.
'20180101') this. width = '20180101'; if (this. offsetHeight> '20180101') this. height = '20180101'; "border = 0>
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.

The code is as follows:


// 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"Title:". $ Th-> title ."
";
Echo"Author:". $ Th-> author ."
";
Echo"Content:

”.$th->content.”
";
Echo "";
}
?>


View the running result 3 in the browser.
'20180101') this. width = '20180101'; if (this. offsetHeight> '20180101') this. height = '20180101'; "border = 0>

Bytes. In practical applications, some simple and less secure data often uses XML files...

Related Article

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.