A summary of how PHP operates XML files

Source: Internet
Author: User
A summary of how PHP operates XML files

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.

 
   
  
   WelcomeSimon 
  
   
    
   Welcome to XML guestbook!!
  
    
 
  


Which, tagged with a tag 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 the standard version information to identify the starting and XML data for the 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 practical applications, the interaction between PHP and XML is very widely used. The SimpleXML component is a new addition to the PHP5
Single XML operations component, the use of simplexml components is straightforward compared to traditional XML components. This section will use the
SimpleXML component Operation XML method to do a detailed introduction.
2.1 Creating a SimpleXML Object
SimpleXML objects are temporary variables 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)
The data variable here is used to store the XML. The following code creates a SimpleXML object using the Simplexml_load_string function

  
 
   
    
    
      Production support 
     
     
      
      
        100001 
       
      
        Simon 
       1982-11-06 
       
       
      
        5000.00 
       
      
        1000.00 
       
      
      
      
        100002 
       
      
        Elaine 
       
      
        1982-01-01 
       
      
        6000.00 
       
      
        2000.00 
       
      
     
    
    
    
      Testing Center  
      
       
       
         110001 
        
       
         Helen 
        
       
         1983-07-21 
        
       
         5000.00 
        
       
         1000.00  
       
       
      
    
    
  
 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 [Employees] = SimpleXMLElement Object ([employee] = = Array ([0] = Simplexmle Lement Object ([serial_no] = 100001 [name] + Simon [age] [Birthday] = 1982-11-06 [salary] + 5000 . xx [Bonus] = 1000.00) [1] = SimpleXMLElement Object ([serial_no] = 100002 [name] + Elaine [age] + 2 4 [Birthday] = 1982-01-01 [Salary] = 6000.00 [Bonus] = 2000.00))) [1] = = SimpleXMLElement Object ([NA ME] = 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.

 
  


where Example.xml stores the same data 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 an SimpleXML object
describes the use of the Print_r function to read the data in the SimpleXML object, which returns the result 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. The Var_dump function displays 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. The
Copy code code is as follows:
!--? php $xml = simplexml_load_file (' example.xml ');//Create SimpleXML Object Var_dump ($xml);//output XML?-->
The
Run results 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.

 
  


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.

 
  


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.

 
  


The results of the operation are as follows.


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.

 
  


The results of the operation are as follows.
The code is as follows:



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.

 
  


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.

 
  


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.

 
  


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.

Copy the code code as follows:

 
  


The output results are as follows.

 
   
 
   
  
    
   
     
    
      
     
      
       
      100001
     
       
    
      
   
     
  
    
 
  



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

 
  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.



The results of the operation are as follows.


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.

The code is as follows:

 
   
 
   
  
    
   
    Here's the title of the message.Here is the message 
   
    
     
    , here is the
   message content
     
  
    
 
  



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 code is as follows:

  Post a new message 
 
     

Post a new message



The basic logic for a PHP script to handle user input is to create a DOM object first, then read the XML data from the XML file, create a new node on the XML object, store the user's input, and finally output the XML data to the original XML file. The implementation code is shown below.
The code is as follows:

 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
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.
The code is as follows:

 
  Thread as $th)//iterate through each thread tag in the XML data {echo " title:". $th->title. "
”; echo " Author:" $th->author. "
”; echo " content:
". $th->content."
  • 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.