_php techniques for using SimpleXML to process XML files under PHP

Source: Internet
Author: User
Tags new set xpath
1 SimpleXML Profile
There are two traditional ways to deal with XML files: SAX and Dom. SAX is based on the event triggering mechanism,
A scan of the XML file completes the processing to be done; the DOM constructs the entire XML file as a DOM
Tree to complete processing by traversing the DOM tree. Both of these methods have their own advantages and disadvantages, and the processing ideas of SAX are relatively abstract,
DOM is a relatively cumbersome process, and is not very suitable for beginners.
PHP5 introduced a new set of XML processing functions, namely simplexml. Name as in fact, SimpleXML itself small
Smart, only provides a small number of method functions, but the use of it to deal with the XML file function is very powerful, the operation is
It's very simple.
First, it provides a simple function that can be constructed directly from an XML document, a string, or a DOM object
SimpleXMLElement object; Second, SimpleXMLElement provides a simple way to make properties, sub sections
Point, and XPath operations; however, the simplest place for SimpleXML is that it provides properties that use standard objects and
The method of node operation of object iterator, which makes the processing of XML document with PHP greatly
of simplification.
2 SimpleXML Getting Started sample
Let's take a look at some small snippets of code to learn a little bit about the power and simplicity of simplexml. For the convenience of example,
We use a Messages.xml file that contains such a piece of XML code:
Messages.xml
Copy Code code as follows:

<?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= ' one ' >reply 1</reply>
<reply id= ' a ' >reply 2</reply>
</msg>
</Messages>

This is an XML document with message information, each message includes attribute ID, child node title, content, time
As well as a number of responses to it, each reply includes the attribute ID and the content of the reply.
The process of processing and outputting the contents of this XML document with SimpleXML and the following methods.
(1) Constructing SimpleXMLElement objects

Code Snippets
$xml = simplexml_load_file (' Messages.xml ');
If this XML has been read into a string $messages, you can use the following statement:
Code Snippets
$xml = simplexml_load_string (' Messages.xml ');
(2) Output message 1 title
Code Snippets
You can access the child nodes by using the properties, and you can get the contents of the nodes directly through the tag names of the nodes.
echo $xml->msg->title;
(3) Output message 1 of the first reply message
Code Snippets
Multiple nodes of the same name automatically become arrays at the same level, and their contents can be accessed by index subscript
echo $xml->msg->reply[0];
(4) The ID of the output message
Code Snippets
The properties and values of the nodes are encapsulated into the keys and values of the associative array
echo $xml->msg[' id '];
(5) Output the ID of the second reply
Code Snippets
As a two-dimensional array, the first dimension represents the node, and the second dimension represents the property
echo $xml->msg->reply[1][' id '];
(6) Output the ID of all replies in turn
Code Snippets
Traversing a node of the same name using foreach
foreach ($xml->msg->reply as $reply) {
echo $reply [' id '];
}
(7) Use XPath to retrieve all reply information
Code Snippets
XPath method retrieves the location directly (//indicates any depth)
foreach ($xml->xpath ('//reply ') as $reply) {
echo $reply. ' <br> ';
}

(8) Traverse message 1 All the child nodes
Code Snippets
Children method to get all child nodes
foreach ($xml->msg->children () as $field) {
echo $field. ' <br> ';
}
(9) Reset the release time of message 1
Code Snippets
Set properties directly
$xml->msg->time = ' 2008-03-21 00:53:12 ';
(10) Set the id attribute of reply 2
Code Snippets
Set the value of an administrative array
$xml->msg->reply[1][' id '] = ' 222 ';
(11) Add a field that describes the message author
Code Snippets
Set properties directly
$xml->msg->author = ' Zhangsan ';
(12) Save the author of the message as a property
Code Snippets
Set key for associative array
$xml->msg[' author '] = ' zhangsan ';
(13) Re-save object to file
Code Snippets
Save
$xml->asxml (' messagesnew.xml ');
Should be able to see how simple simplexml it!
3 instance: Data interaction between XML file and database
Below provides a relatively complete example, the message information from the MySQL database query out, save as a
An XML file as shown in the example above. Message and reply information are saved separately in two tables, using MySQL function package
The following can be achieved very simply:

The code is as follows:
Copy Code code as follows:

<?php
Cong work atwed Mar 19:59:04 CST 2008
Saving data from a MySQL database to an XML file
You can construct the initial SimpleXMLElement object in several ways:
1. Constructing from DOM objects
$dom = new DOMDocument ();
$dom->loadxml ("<rows></rows>");
$xml = Simplexml_import_dom ($dom);
2. Construct from XML file containing only root tag
$xml = simplexml_load_file (' Messages.xml ');
3, directly write the root tag string construction
$xml = simplexml_load_string ("<Messages></Messages>");
4. Constructor construction using SimpleXMLElement class
$xml = new SimpleXMLElement (' <Messages></Messages> ');
Connecting to a database
mysql_connect (' localhost ', ' root ', ' root ');
mysql_select_db (' Test ');
mysql_query (' Set names UTF8 ');
Query messages
$rs = mysql_query ("SELECT * from messages");
$i = 0; Array index subscript to be used for more than one message
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 for its related reply information based on the message ID
$rsReply = mysql_query ("select * from replies where mid={$row [' ID ']}");
$j = 0; Index subscript 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 here is the line that marks ①. When we are going to a SimpleXML object in the new
When you add a node or attribute, you must ensure that its parent node is present, or you will report a fatal error, indicating that the message is:
Objects used as arrays in Post/pre increment/decrement must return values by reference. Hope everyone

Don't be fooled by this unintelligible hint. I believe that the reader can, by understanding the above code, write a code from the XML file to MySQL.

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.