Use SimpleXML in php to process XML files

Source: Internet
Author: User
There are two traditional approaches to processing XML files: SAX and DOM. 1 SimpleXML introduction
There are two traditional approaches to processing XML files: SAX and DOM. Based on the event trigger mechanism,
Scan the XML file once to complete the processing. DOM constructs the entire XML file into a DOM
To process the DOM tree. The two methods have their own advantages and disadvantages. the processing logic of SAX is relatively abstract,
The DOM processing process is cumbersome and is not suitable for beginners.
PHP5 introduces a new set of XML processing functions, namely SimpleXML. SimpleXML is actually small.
Coincidentally, only a few method functions are provided, but the XML file processing function is very powerful.
Very simple.
First, it provides simple functions that can be directly constructed from XML documents, strings, or DOM objects.
SimpleXMLElement object. Secondly, SimpleXMLElement provides a simple method for attributes and subsections.
Point, and XPath operations; however, the simplest thing about SimpleXML is that it provides the attributes and
The method used by the object iterator to perform node operations. this processing method greatly improves the processing of XML documents with PHP.
.
2 SimpleXML getting started example
Below we will take a look at the power and conciseness of SimpleXML through some small code snippets. For convenience,
We use a Messages. xml file that contains the following XML code:
Messages. xml
The code is as follows:



This is Title
Here is Content
2008-03-20 21:50:23
Reply 1
Reply 2



This is an XML document that stores message information, including the property id, subnode title, content, and time.
And a number of response information for it. each response includes the attribute id and response content.
The process and method for processing and outputting the content of this XML document using SimpleXML are as follows.
(1) construct SimpleXMLElement object

Code snippet
$ Xml = simplexml_load_file ('messages. XML ');
If the xml segment has been read into a string $ messages, you can use the following statement:
Code snippet
$ Xml = simplexml_load_string ('messages. XML ');
(2) output the title of message 1
Code snippet
// You can use attributes to access the subnode. you can directly obtain the node content by using the label name of the node.
Echo $ xml-> msg-> title;
(3) output the first reply message in message 1.
Code snippet
// Multiple nodes with the same name at the same level automatically become an array and their content can be accessed through index subscript
Echo $ xml-> msg-> reply [0];
(4) id of the output message
Code snippet
// Node attributes and values are encapsulated into keys and values of the associated array.
Echo $ xml-> msg ['id'];
(5) output the id of the second reply
Code snippet
// It is a two-dimensional array. The first dimension indicates the node and the second dimension indicates the attribute.
Echo $ xml-> msg-> reply [1] ['id'];
(6) output the IDs of all replies in sequence
Code snippet
// Use foreach to traverse nodes with the same name
Foreach ($ xml-> msg-> reply as $ reply ){
Echo $ reply ['id'];
}
(7) Use XPath to retrieve all reply information
Code snippet
// Direct retrieval and location using the xpath method (// represents any depth)
Foreach ($ xml-> xpath ('// reply') as $ reply ){
Echo $ reply .'
';
}

(8) traverse message 1 all subnodes
Code snippet
// Obtain all child nodes using the children method
Foreach ($ xml-> msg-> children () as $ field ){
Echo $ field .'
';
}
(9) reset the release time of message 1.
Code snippet
// Directly set attributes
$ Xml-> msg-> time = '2017-03-21 00:53:12 ';
(10) set the id attribute of reply 2
Code snippet
// Set the value of the management array
$ Xml-> msg-> reply [1] ['id'] = '2013 ';
(11) add a field describing the message author.
Code snippet
// Directly set attributes
$ Xml-> msg-> author = 'hangsan ';
(12) save the message author as an attribute
Code snippet
// Set the key of the associated array
$ Xml-> msg ['autor'] = 'hangsan ';
(13) save the object to the file again
Code snippet
// Save
$ Xml-> asXML ('messagesnew. XML ');
We can see how simple SimpleXML is!
3. example: data interaction between XML files and databases
The following provides a relatively complete instance to query the message information from the MySQL database and save it
As shown in the preceding example. The message and reply information are stored in two tables independently, using the MySQL function package
It can be easily implemented as follows:

The code is as follows:
The code is as follows:
// Cong work atWed Mar 20 19:59:04 CST 2008
// Save the data from the MySQL database to the XML file
// You can use the following methods to construct the initial SimpleXMLElement object:
// 1. construct from the DOM object
// $ Dom = new DOMDocument ();
// $ Dom-> loadXML (" ");
// $ Xml = simplexml_import_dom ($ dom );
// 2. construct from an xml file containing only the root tag
// $ Xml = simplexml_load_file ('messages. XML ');
// 3. directly write the root tag string to construct
// $ Xml = simplexml_load_string (" ");
// 4. use the constructor of the SimpleXMLElement class to construct
$ Xml = new SimpleXMLElement (' ');
// Connect to the database
Mysql_connect ('localhost', 'root', 'root ');
Mysql_select_db ('test ');
Mysql_query ('set names utf8 ');
// Query a message
$ Rs = mysql_query ("select * from messages ");
$ I = 0; // index the subscript with an array of multiple messages
While ($ row = mysql_fetch_assoc ($ rs )){
$ Xml-> message [$ I] = '';//... ... ... ... ... ... ... ... ... ... ... ... ①
$ Xml-> message [$ I] ['id'] = $ row ['id'];
$ Xml-> message [$ I]-> title = $ row ['title'];
$ Xml-> message [$ I]-> content = $ row ['content'];
$ Xml-> message [$ I]-> time = $ row ['Time'];
// Query the reply information of a message based on the message id.
$ RsReply = mysql_query ("select * from replies where mid = {$ row ['id']}");
$ J = 0; // Index subscript used for multiple replies
While ($ rowReply = mysql_fetch_assoc ($ rsReply )){
$ Xml-> message [$ I]-> reply [$ j] = $ rowReply ['reply'];
$ Xml-> message [$ I]-> reply [$ j] ['id'] = $ rowReply ['id'];
$ J ++;
}
$ I ++;
}
$ Xml-> asXML ('messages. XML ');
?>

The only thing worth mentioning in the above code is the line marked as ①. When we want to add a new
When adding a node or attribute, you must ensure that its parent node exists. Otherwise, a fatal error is reported and the message is:
Objects used as arrays in post/pre increment/decrement must return values by reference. Hope everyone

Do not be confused by the prompt of the migration cloud. I believe that readers can write a code from an XML file to MySQL through their understanding of the above code.

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.