Analysis of various php xml operations (more detailed)

Source: Internet
Author: User
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. 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.

  
  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.

The data variable is used to store XML data. The following code creates a SimpleXML object using the simplexml_load_string function:

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

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] => 5000.00 [bonus] => 1000.00 ) [1] => SimpleXMLElement Object ( [serial_no] => 100002 [name] => Elaine [age] => 24 [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] => 23 [birthday] => 1983-07-21 [salary] => 5000.00 [bonus] => 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.

 

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 running result 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:
.

 depart as $a) { 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.

 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.

 Depart-> children () as $ depart) // read the sub-Tag {var_dump ($ depart) under the depart tag cyclically; // output the XML data of the tag}?>

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

 Xpath ('/departs/depart/employees/employee/name'); // defines the node var_dump ($ result); // output node?>

The running result is 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” } }

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.

 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.

 AsXML (); // standard 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.

 AsXML (); // standardized XML data $ fp = fopen ("newxml. xml "," w "); // open the file fwrite ($ fp, $ newxml) to write XML data; // 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.

 CreateElement ('parts'); $ dom-> appendChild ($ departs ); // create the depart sub-tag $ depart = $ dom-> createElement ('demopart') under the departs tag; $ departs-> appendChild ($ depart ); // create a child employees tag under the depart tag $ employees = $ dom-> createElement ('ployees'); $ depart-> appendChild ($ employees ); // under the employees tag, create the employee sub-tag $ employee = $ dom-> createElement ('employee'); $ employees-> appendChild ($ employee ); // create serial under the employee tag _ No sub-tag $ serial_no = $ dom-> createElement ('serial _ no'); $ employee-> appendChild ($ serial_no ); // add the value node 100001 $ serial_no_value = $ dom-> createTextNode ('000000') for the serial_no label; $ 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 reads the XML file.

 Load ('example. XML'); // read the xml file $ root = $ dom-> documentElement; // Obtain the XML data root read_child ($ root ); // call the read_child function to read the root object function read_child ($ node) {$ children = $ node-> childNodes; // obtain all the subnodes of $ node foreach ($ children as $ e) // read each subnode cyclically {if ($ e-> nodeType = XML_TEXT_NODE) // if the subnode is text, the output is {echo $ e-> nodeValue."
";} Else if ($ e-> nodeType = XML_ELEMENT_NODE) // if the child node is a node object, call the function to process {read_child ($ e) ;}}?>

The running result is as follows.

Reference to 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.

  
  
   
   Here is the message titleHere 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.

  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.

 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 $ title = $ guestbook-> createElement ('title') on the new thread node '); $ 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 $ content = $ guestbook-> createElement ('content') on the new thread node '); $ content-> appendChild ($ guestbook-> createTextNode ($ _ POST ['content']); $ thread-> appendChild ($ content ); // write XML data to the file $ fp = fopen ("DB/guestbook. xml "," w "); if (fwrite ($ fp, $ guestbook-> saveXML () echo "Message submitted successfully"; else echo "message submitted failed"; fclose ($ fp);?>

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

The display page can be easily implemented using the SimpleXML component described earlier. the specific implementation code is as follows.

 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.

For more information about php xml operations, see The PHP Chinese website!

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.