PHP XML operations of various methods parsing (more detailed) _php tutorial

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

Welcome
Simon
Welcome to XML guestbook!!


which with the Tag labeled 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 To identify the start of XML data and XML data using standard version information. Accessing the XML file in the browser can see the hierarchical XML data information, shown in 1.
' This.width= '), if (this.offsetheight> ' ") this.height= '", "border=0>
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
Copy CodeThe code is as follows:
$data = <<


Production support


100001
Simon
24
1982-11-06
5000.00
1000.00


100002
Elaine
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 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.
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] = 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
)
)
)
)
)

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.
Copy CodeThe code is as follows:
$xml = simplexml_load_file (' Example.xml '); Create a 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.
Copy CodeThe code is as follows:


The results of the operation are as follows.
Copy CodeThe code is as follows:
Object (SimpleXMLElement) #1 (1) {["Depart"]=> Array (2) {
[0]=>
Object (SimpleXMLElement) #2 (2) {
["Name"]=>
String ("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 (+) "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 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.
Copy CodeThe code is as follows:
Depart as $a)
{
echo "$a->name
”;
}
?>

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.
Copy CodeThe code is as follows:
$xml = simplexml_load_file (' Example.xml '); Reading an 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.
Copy CodeThe code is as follows:
$xml = simplexml_load_file (' Example.xml ');
foreach ($xml->depart->children () as $depart)//Looping through depart label Sub-labels
{
Var_dump ($depart); XML data for output labels
}
?>

The results of the operation are as follows.
Copy CodeThe code is 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"]=>
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.
Copy CodeThe code is as follows:
$xml = simplexml_load_file (' Example.xml '); Reading an XML file
$result = $xml->xpath ('/departs/depart/employees/employee/name '); Defining nodes
Var_dump ($result); Output node
?>

The results of the operation are 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) "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.
Copy CodeThe code is as follows:
$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.
Copy CodeThe code is as follows:
$xml = simplexml_load_file (' Example.xml '); Reading 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.
Copy CodeThe code is as follows:
$xml = simplexml_load_file (' Example.xml '); Reading XML data
$newxml = $xml->asxml (); Standardize XML data
$fp = fopen ("Newxml.xml", "w"); Open the file you want to write XML data to
Fwrite ($fp, $newxml); Writing 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.

Copy CodeThe code is as follows:
To create a new DOM document
$dom = new DomDocument ();
Create a departs label on the root node
$departs = $dom->createelement (' departs ');
$dom->appendchild ($departs);
Create depart sub-labels under the Departs tab
$depart = $dom->createelement (' Depart ');
$departs->appendchild ($depart);
Create employees sub-labels 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);
Adding values to the SERIAL_NO tag node 100001
$serial _no_value = $dom->createtextnode (' 100001′);
$serial _no->appendchild ($serial _no_value);
Output XML data
echo $dom->savexml ();
?>
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.
Copy CodeThe code is as follows:
$dom = new DomDocument (); Creating DOM objects
$dom->load (' example.xml '); Reading an XML file
$root = $dom->documentelement; Gets the root of the XML data
Read_child ($root); Call the Read_child function to read the root object
function Read_child ($node)
{
$children = $node->childnodes; Get all child nodes of $node
foreach ($children as $e)//looping through each child node
{
if ($e->nodetype = = xml_text_node)//output if child nodes are text type
{
echo $e->nodevalue. "
”;
}
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.
Copy CodeThe code is as follows:
Reference
Production support
100001
Simon
24
1982-11-06
5000.00
1000.00
100002
Elaine
24
1982-01-01
6000.00
2000.00
Testing Center
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.

Copy CodeThe code is as follows:



Here's the title of the message.
This 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.
Copy CodeThe code is as follows:


<title>Post a new message</title>



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.
Copy CodeThe code is as follows:
$guestbook = new DomDocument (); To create a new DOM object
$guestbook->load (' db/guestbook.xml '); Reading 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 a new thread node
$content = $guestbook->createelement (' content ');
$content->appendchild ($guestbook->createtextnode ($_post[' content '));
$thread->appendchild ($content);
Writing 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 above HTML file in the browser and fill in the appropriate message content, as shown in 2.
' This.width= '), if (this.offsetheight> ' ") this.height= '", "border=0>
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.
Copy CodeThe code is as follows:
Open the XML file for storing messages
$guestbook = simplexml_load_file (' Db/guestbook.xml ');
foreach ($guestbook->thread as $th)//iterate through each thread label in the XML data
{
echo " Title:". $th->title."
”;
echo " Author:". $th->author."
”;
echo " content:
". $th->content."
”;
echo "";
}
?>


Look in the browser to see the results of the run 3 shown.
' This.width= '), if (this.offsetheight> ' ") this.height= '", "border=0>

http://www.bkjia.com/PHPjc/322160.html www.bkjia.com true http://www.bkjia.com/PHPjc/322160.html techarticle 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 used in XML file ...

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