Parsing of various methods of PHP XML operations (more detailed)

Source: Internet
Author: User
XML is a popular semi-structured file format that stores data in a database-like format. In practical applications, some simple, low-security data is often stored in the format of an XML file. The benefits of this can be achieved by reducing the interaction with the database to improve the reading efficiency, on the other hand can effectively use the advantages of XML to reduce the programming difficulty.
PHP provides a complete set of methods for reading XML files, and it is easy to write an XML-based script program. This chapter will introduce the operation methods of PHP and XML, and make a brief introduction to several commonly used XML class libraries.
1 Introduction to XML
XML is an abbreviation for "Extensible Identity Language (extensible Markup Language)" and is a markup language similar to HTML. However, unlike HTML, XML is primarily used to describe data and hold data, while HTML is primarily used to display data.
XML is a "meta-markup" language that allows developers to create the name of a tag according to their needs. For example, the following XML code can be used to describe a message.

<thread> <title>Welcome</title> <author>Simon</author> <content>welcome to XML guestbook!! </content> </thread>

where,<thread> with </thread> tag tagged this is a message. In the message there is a title, the author, the content, the complete expression of a message message.
At the top of an XML file, you typically use <?xml version= "1.0″?> to identify the beginning of XML data and the use of standard version information for XML data. Accessing the XML file in the browser can see the hierarchical XML data information, shown in 1.

XML is developing very quickly, and in recent years many software developers have started to use XML development standards for application development. Also, many emerging technologies are architected on top of XML data. This means that XML will become an integral part of web technology as well as HTML.
2 Simple XML Operations
in practice, PHP interacts with XML in a wide variety of applications. The SimpleXML component is an XML operational component that PHP5 a new addition to the simple
single, and the use of simplexml components is straightforward compared to traditional XML components. This section provides a detailed description of how XML is manipulated using the
SimpleXML component.
2.1 Creates a SimpleXML object
SimpleXML object is a temporary variable used to temporarily store XML data, and operations on XML are done by manipulating the SimpleXML object. The SimpleXML component provides two methods for creating SimpleXML objects. The first method is to use the Simplexml_load_string function to read the XML data in a string variable to complete the creation, with the syntax format shown below.
Simplexml_load_string (String data)
Here is used to store XML data. The following code uses the Simplexml_load_string function to create a SimpleXML object

<?php $data = <<<xml//define 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>Elaine</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 SimpleXML Object Print_r ($xml); Output XML?>

In the example above, the $DATA variable stores an XML data. The simplexml_load_string function converts the variable $data into a SimpleXML object. The structure of the object can be seen through the output of the Print_r function, and the result is as follows.

SimpleXMLElement object ([depart] = = Array ([0] = simplexmlelement object ([name] = Production support [Empl Oyees] = simplexmlelement object ([employee] = = Array ([0] = simplexmlelement object ([serial_no] = 1000 [Name] + Simon [age] [Birthday] = 1982-11-06 [Salary] = 5000.00 [Bonus] = 1000.00) [1] = =  SimpleXMLElement Object ([serial_no] = 100002 [name] = Elaine [age] [Birthday] = 1982-01-01 [Salary] = = 6000.00 [Bonus] = 2000.00)]) [1] = = SimpleXMLElement Object ([name] + Testing Center [Employees] = > SimpleXMLElement object ([Employee] = simplexmlelement object ([serial_no] = 110001 [name] = Helen [age ] = [Birthday] = 1983-07-21 [Salary] = 5000.00 [Bonus] = 1000.00))))

As you can see from the output, the structure of the SimpleXML object is exactly the same as the format of the XML data.
The second method is to use the Simplexml_load_flie function to read an XML file to complete the creation, with the syntax format shown below.
Simplexml_load_file (string filename)
The filename variable here is the file name and path where the XML data file is stored. The following code uses the Simplexml_load_file function to create a SimpleXML object.

<?php $xml = simplexml_load_file (' Example.xml '); Create SimpleXML Object Print_r ($xml); Output XML?>

The data stored by Example.xml is exactly the same as the above $data, and the result is exactly 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 a php script file, you need to use simplexml_load_string to create it. If the XML data source is in a separate XML file, you need to use simplexml_load_file to create it.
2.2 Reading XML data from a SimpleXML object
The previous article describes using the Print_r function to read the data in the SimpleXML object, and its return result is similar to the structure of the array. Obviously, this kind of display method is not advisable in practical application. Here are a few other ways to read the XML data in the SimpleXML object.
1. Var_dump function Display Object details
The Var_dump function can be used to display details of the SimpleXML object, and the Var_dump function displays more complete information than the Print_r function, as shown in the following syntax.
void Var_dump (Object1, object2 ...)
The following code uses the Var_dump function to output the details of the object in the above example.

<?php $xml = simplexml_load_file (' Example.xml '); Create SimpleXML Object Var_dump ($xml); Output XML?>

The results of the operation are as follows.

Object (SimpleXMLElement) #1 (1) {["Depart"]=> Array (2) {[0]=> object (simplexmlelement) #2 (2) {["Name"]=> Strin G (+) "Production support" ["Employees"]=> object (SimpleXMLElement) #4 (1) {["Employee"]=> Array (2) {[0]=> Obje CT (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" Testing Center "[" Employees "]=&G T 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"]=& Gt String (7) "1000.00″}}}}}

Compared with the results of the previous Print_r output, the output of the Var_dump function is more rigorous and the data type of each attribute in the object is analyzed. In practical applications, the Var_dump function is often used for object detection during program debugging.
2. Reading tags in XML data
Like variables that manipulate array types, reading XML can be done in a similar way. For example, if you need to read the "name" property under each "depart" tag in the XML data above, you can do so by using the Foreach function, such as the following code
is shown.

<?php $xml = simplexml_load_file (' Example.xml '); foreach ($xml->depart as $a) {echo "$a->name <BR>";}?>

The results of the operation are as follows.
Production support
Testing Center
Reads an XML file//loops through every depart tag in the XML data
Output the Name property
You can also use square brackets "[]" to directly read the label specified in the XML data. The following code outputs the "name" property of the first "depart" label in the XML data above.

<?php $xml = simplexml_load_file (' Example.xml '); Read the XML file echo $xml->depart->name[0]; Output Node?>

The results of the operation are as follows.
Production support
For all sub-labels under a label, the SimpleXML component provides the children method for reading. For example, for the "depart" label in the XML data above, it includes two sub-Tags: "name" and "Employees". The following code implements the read of the sub-label under the first "depart" label.

<?php $xml = simplexml_load_file (' Example.xml '); foreach ($xml->depart->children () as $depart)//Loop reads sub-label {var_dump ($depart) under Depart label,//Output tag XML data}?>

The results of the operation are as follows.

Object (SimpleXMLElement) #3 (1) {[0]=> string () "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 "]=&G T String (6) "Elaine" ["Age"]=> string (2) "24″[" Birthday "]=> string (10)" 1982-01-01″["Salary"]=> string (7) " 6000.00″["Bonus"]=> string (7) "2000.00″}}}

As you can see, all sub-tags are treated as a new XML file after using the children method.
3. Query based on XML data path
The SimpleXML component provides a query method based on an XML data path. The XML data path is the entire label that passes from the root of the XML to a label. This path uses a slash "/" to separate the label name. For example, for the above XML data, to query for all the values in the label "name", from the root to go through the departs, depart, employees, and employee tags, the path
To "/departs/depart/employees/employee/name". The SimpleXML component uses the XPath method to parse the path with the syntax format shown below.
XPath (string path)
Where path is the route. The method returns an array that contains all the tag values to query. The following code queries all the name tags in the XML data above.

<?php $xml = simplexml_load_file (' Example.xml '); Read XML file $result = $xml->xpath ('/departs/depart/employees/employee/name '); Define node Var_dump ($result); Output Node?>

The results of the operation are as follows.

Array (3) {[0]=> object (simplexmlelement) #2 (1) {[0]=> string (5) "Simon"} [1]=> object (simplexmlelement) #3 (1) {[0]=> string (6) "Elaine"} [2]=> object (simplexmlelement) #4 (1) {[0]=> string (5) "Helen"}}

As you can see, all the name tags are queried.
2.3 Modification of XML data
Modifying the XML data is similar to reading the label method in XML data. This is done by directly modifying the value of the label in the SimpleXML object. The following code implements the modification of the "name" sub-label of the first "depart" label in the XML data above.

<?php $xml = simplexml_load_file (' Example.xml '); Read XML $xml->depart->name[0] = "Human Resource"; Modify Node?>

The modification does not have any effect on the XML file. However, in the program, the read for the SimpleXML object will use the modified value.
2.4 Standardizing XML data
SimpleXML also provides a method asxml for standardizing XML data. The Asxml method effectively re-orchestrates the contents of the SimpleXML object according to the XML 1.0 standard and returns it as the data type of the string. The following code implements the normalization of the XML data above.

<?php $xml = simplexml_load_file (' Example.xml '); Read XML data echo $xml->asxml (); Standardize XML Data?>

2.5 Storage of XML data
The method of storing XML data in an SimpleXML object into an XML file is very simple and will 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.

<?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 which you want to write XML data fwrite ($FP, $newxml); Writes XML data fclose ($FP); Close File?>

After the code runs, you can see the XML data in the Newxml.xml file as shown below.
As you can see, modifications to the XML file have been saved in the output file.
3 Dynamic creation of XML documents
In real-world applications, it is sometimes necessary to dynamically generate XML document operations. The SimpleXML component described earlier does not provide a way to create an XML document. Therefore, if you need to create XML documents dynamically, you often create them using DOM components. The DOM is the abbreviation for the Document Object model, object, and the DOM component provides a tree-type parsing pattern of the XML document. The following code creates an XML document using the DOM component.

<?php//Create a new DOM document $dom = new DomDocument (); Create a departs tag on the root node $departs = $dom->createelement (' departs '); $dom->appendchild ($departs); Create the Depart sub-label under the departs tab $depart = $dom->createelement (' Depart '); $departs->appendchild ($depart); Create the Employees sub-label under the depart tab $employees = $dom->createelement (' employees '); $depart->appendchild ($employees); Create an employee sub-label under the employees tab $employee = $dom->createelement (' employee '); $employees->appendchild ($employee); Create a Serial_no sub-label under the employee tab $serial _no = $dom->createelement (' serial_no '); $employee->appendchild ($serial _no); Add a value node for the serial_no tag 100001 $serial _no_value = $dom->createtextnode (' 100001′ '); $serial _no->appendchild ($serial _no_value); Output XML data echo $dom->savexml ();?> output is shown below. <?xml version= "1.0″?> <departs> <depart> <employees> <employee> <serial_no> 100001</serial_no> </employee> </employees> </depart> </departs>

DOM components can also be used to read XML files in addition to the ability to dynamically create XML documents. The following code implements a read of the preceding XML file.

<?php $dom = new DomDocument (); Create a DOM object $dom->load (' example.xml '); Read XML file $root = $dom->documentelement; Gets the root read_child ($root) of the XML data; Call the Read_child function to read the root object functions Read_child ($node) {$children = $node->childnodes;//Get all the child nodes of the $node foreach ($children As $e)//iterate through each child node {if ($e->nodetype = = Xml_text_node)///If the child node is text type then output {echo $e->nodevalue. <BR> "; } else if ($e->nodetype = = Xml_element_node)//If the child node is a node object, the calling function handles {read_child ($e);}} }?>

The results of the operation are as follows.

Reference production support 100001 Simon 1982-11-06 5000.00 1000.00 100002 Elaine 1982-01-01 6000.00 2000.00 Testing Cente R 110001 Helen 23 1983-07-21 5000.00 1000.00

The example above uses a recursive approach to XML data processing, which implements the function of all text-type tags in the output XML data.
4 XML Application Example--message book
The basic operation of XML is described earlier in this section, which is an example of designing an XML message to explain in detail how PHP interacts with XML data in practical applications.
4.1 XML File Structure design
XML files are used to store XML data, which is the message in the message book. Here, for each message, in the XML data mainly includes three items: Message title, the name of the message, message content. Therefore, the format of the XML file is designed as follows.

<?xml version= "1.0″?> <threads> <thread> <title> Here is the title of the message </title> <author> here is the message person </author> <content> Here is the message </content> </thread> </threads>

4.2 Writing the submission page
The submit Message page consists of two pages. One is the HTML file for the form that the visitor uses to write the message, and one for the PHP script that handles the visitor's input. The HTML code for the form is shown below.


The basic logic of the

PHP script for handling user input is to create a DOM object first, then read the XML data in the XML file, then create a new node on the XML object and store the user's input, and finally output the XML data to the original XML file. The implementation code is shown below.

<?php $guestbook = new DomDocument (); Create a new DOM object $guestbook->load (' db/guestbook.xml '); Read XML data $threads = $guestbook->documentelement; Get the root of the XML structure//create a new thread node $thread = $guestbook->createelement (' thread '); $threads->appendchild ($thread); Create a title tag on the new thread node $title = $guestbook->createelement (' title '); $title->appendchild ($guestbook->createtextnode ($_post[' title ')); $thread->appendchild ($title); Create a author label on the new thread node $author = $guestbook->createelement (' author '); $author->appendchild ($guestbook->createtextnode ($_post[' author ')); $thread->appendchild ($author); Create a content label on the new thread node $content = $guestbook->createelement (' content '); $content->appendchild ($guestbook->createtextnode ($_post[' content ')); $thread->appendchild ($content); Writes XML data to the 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 above HTML file in the browser and fill in the appropriate message content, as shown in 2.

Figure 2 Publishing a new message interface
When you click the Submit button, the contents of the XML file are as follows.
You can see that the message has been stored in the XML file.
4.3 Writing of the display page
The display page can be easily implemented using the SimpleXML component described earlier, and the implementation code is shown below.

<?php//Open the XML file used to store the message $guestbook = simplexml_load_file (' Db/guestbook.xml '); foreach ($guestbook->thread as $th)//loops through each thread label {echo <B> title:</b> ". $th->title in the XML data." <BR> "; echo "<B> author:</b>". $th->author. " <BR> "; echo "<B> content:</b><pre>". $th->content. " </PRE> "; echo "<HR>"; }?>

Look in the browser to see the results of the run 3 shown.

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.