PHP USES SimpleXML to process XML files

  • 2020-03-31 20:25:11
  • OfStack

1 the SimpleXML profile
There are two traditional ways of working with XML files: SAX and DOM. SAX is based on the event trigger mechanism,
Scan the XML file once to complete the processing; DOM constructs the entire XML file as a DOM
Tree, which is processed by traversing the DOM tree. Both methods have their advantages and disadvantages. The processing idea of SAX is relatively abstract.
The DOM processing process is relatively cumbersome, and is not suitable for beginners to get started.
PHP5 introduces a new set of XML processing functions called SimpleXML. As the name implies, SimpleXML itself is small
Nifty, with only a few method functions, it is very powerful and manipulative for handling XML files
It's very simple.
First, it provides simple functions that can be constructed directly from XML documents, strings, or DOM objects
SimpleXMLElement object; Second, SimpleXMLElement provides an easy way to do attributes, subsections
Operations on points, and XPath; However, the simplest thing about SimpleXML is that it provides properties and properties that use standard objects
The approach of object iterators to node operations, which leads to a great deal of processing of XML documents in PHP
The simplified.
2 sample SimpleXML primer
Let's take a look at the power and simplicity of SimpleXML with some small code snippets. For example,
We use a messages.xml file that contains the following XML code:
XML Messages.
 
<?xml version='1.0' standalone='yes'?> 
<Messages> 
<msg id='1'> 
<title>This is Title</title> 
<content>Here is Content</content> 
<time>2008-03-20 21:50:23</time> 
<reply id='11'>reply 1</reply> 
<reply id='12'>reply 2</reply> 
</msg> 
</Messages> 

This is an XML document containing the message information. Each message includes the attribute id, child node title, content, and time
And several replies to it, each of which includes the attribute id and the content of the reply.
The process and method of processing and outputting the contents of this XML document with SimpleXML are as follows.
(1) construct a SimpleXMLElement object

The code fragment
$XML = the simplexml_load_file (' Messages. The XML).
If this XML has been read into a string $messages, you can use the following statement:
The code fragment
$XML = simplexml_load_string (' Messages. The XML).
(2) output the title of message 1
The code fragment
// child nodes can be accessed in the way of attributes, and the content of the node can be directly obtained by the tag name of the node
Echo $XML - > MSG - > The title;
(3) output the first reply message of message 1
The code fragment
// multiple peers of the same name automatically become an array whose contents can be accessed by index subscripts
Echo $XML - > MSG - > The reply [0].
(4) output the id of the message
The code fragment
The attributes and values of // nodes are encapsulated as the keys and values of an associative array
Echo $XML - > MSG [' id '];
(5) output the id of the second reply
The code fragment
// becomes a two-dimensional array, with the first dimension representing nodes and the second dimension representing properties
Echo $XML - > MSG - > The reply [1] [' id '];
(6) output the ids of all replies in turn
The code fragment
// use foreach to traverse the node of the same name
The foreach ($XML - > MSG - > The reply as ${reply)
Echo $reply [' id '];
}
(7) retrieve all reply messages using XPath
The code fragment
//xpath method directly retrieves the location (// for any depth)
The foreach ($XML - > Xpath (' / / reply) as ${reply)
Echo $reply. '< Br> ';
}

(8) traverse all the child nodes of message 1
The code fragment
The //children method gets all the child nodes
The foreach ($XML - > MSG - > The children () as ${field)
Echo $field. '< Br> ';
}
(9) reset the release time of message 1
The code fragment
// directly sets the properties
$XML - > MSG - > Time = '2008-03-21 00:53:12';
(10) set the id attribute of reply 2
The code fragment
// sets the value of the management array
$XML - > MSG - > The reply [1] [' id '] = '222';
(11) add a field describing the author of the message
The code fragment
// directly sets the properties
$XML - > MSG - > The author = 'zhangsan';
(12) save the author of the message as a property
The code fragment
// sets the key of the associative array
$XML - > MSG = [' author '] 'zhangsan';
(13) re-save the object to a file
The code fragment
/ / save
$XML - > AsXML (' MessagesNew. XML);
You can see how simple SimpleXML is.
Example 3: data interaction between an XML file and a database
Here is a relatively complete example of querying the message information from the MySQL database and saving it as one
As shown in the example above. The message and reply messages are stored in two separate tables using the MySQL function package
It can be implemented very simply as follows:

The code is as follows:
 
<?php 
//cong work atWed Mar 20 19:59:04 CST 2008 
//Save the data from the MySQL database to an XML file
//You can construct an initial SimpleXMLElement object in the following ways
//1. Construct from a DOM object
//$dom = new DOMDocument(); 
//$dom->loadXML("<rows></rows>"); 
//$xml = simplexml_import_dom($dom); 
//Construct from an XML file that contains only the root tag
//$xml = simplexml_load_file('messages.xml'); 
//3. Write the root tag string directly
//$xml = simplexml_load_string("<Messages></Messages>"); 
//4. Construct using the constructor of the SimpleXMLElement class
$xml = new SimpleXMLElement('<Messages></Messages>'); 
//Connect to database
mysql_connect('localhost','root','root'); 
mysql_select_db('test'); 
mysql_query('set names utf8'); 
//Query message
$rs = mysql_query("select * from messages"); 
$i = 0; //Used as an index index of an array of messages
while($row = mysql_fetch_assoc($rs)){ 
$xml->message[$i] = ''; // ...   ...   ...   ...   ...   ...   ...   ...   ...   ...   ...   ...   1.  
$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 response information associated with the message by its id
$rsReply = mysql_query("select * from replies where mid={$row['id']}"); 
$j = 0; //An index index used to make 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 about the above code is the line marking. When we want to start with a SimpleXML object
When a node or attribute is added, its parent node must be guaranteed to exist, otherwise a fatal error will be reported. The message is:
Objects used as arrays in post/pre increment/decrement must return values by reference. I hope you

Don't be fooled by this rambling reminder. It is believed that the reader can write an equivalent code from the XML file to MySQL through the understanding of the above code.

Related articles: