Using SimpleXML to process XML files under PHP _php tutorial

Source: Internet
Author: User
Tags xpath
1 SimpleXML Introduction
There are two traditional ways to work with XML files: SAX and Dom. SAX is based on the event triggering mechanism,
The XML file is scanned for processing, and the DOM constructs the entire XML file as a DOM
Tree, through the traversal of the DOM tree to complete processing. Both of these methods have advantages and disadvantages, and SAX is relatively abstract in its processing.
DOM processing is relatively cumbersome, and is not very suitable for beginners to get started.
PHP5 introduced a new set of XML processing functions, called simplexml. Name as in fact, SimpleXML itself small
Ingenious, only provides a small number of methods functions, but with it to handle the XML file function is very powerful, operation also
It's very simple.
First, it provides simple functions that can be constructed directly from an XML document, a string, or a DOM object.
SimpleXMLElement object; Second, SimpleXMLElement provides a simple way to perform attributes, sub-sections
Point, and XPath operations; however, the simplest part of SimpleXML is that it provides properties that use standard objects and
Object iterator is a method of node operation, which makes the processing of XML documents with PHP greatly
The simplified.
2 SimpleXML Getting Started example
Let's take a look at some small snippets of code to get a little bit of SimpleXML's power and simplicity. For illustrative purposes,
We use a Messages.xml file that contains an XML code like this:
Messages.xml
Copy CodeThe 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 holds message information, each of which includes the attribute ID, the child node title, content, time
and several reply messages for it, each reply includes the property ID and the content of the reply.
The process and methods for processing and outputting the contents of this XML document with SimpleXML are as follows.
(1) Constructing SimpleXMLElement objects

Code Snippets
$xml = simplexml_load_file (' Messages.xml ');
If this XML has already been read into a string $messages, you can use the following statement:
Code Snippets
$xml = simplexml_load_string (' Messages.xml ');
(2) The title of output message 1
Code Snippets
Child nodes can be accessed using attributes, and the node's contents can be directly obtained through the tag name of the node
echo $xml->msg->title;
(3) Output message 1 The first reply message
Code Snippets
Multiple nodes of the same name at the same level automatically become arrays that can be indexed to access their contents
echo $xml->msg->reply[0];
(4) The ID of the output message
Code Snippets
The properties and values of a node are encapsulated as keys and values of an associative array
echo $xml->msg[' id '];
(5) Output the ID of the second reply
Code Snippets
becomes a two-dimensional array, the first dimension represents the node, and the second dimension represents the attribute
echo $xml->msg->reply[1][' id '];
(6) Output the ID of all replies in turn
Code Snippets
Using foreach to traverse a node of the same name
foreach ($xml->msg->reply as $reply) {
echo $reply [' id '];
}
(7) Use XPath to retrieve all reply messages
Code Snippets
XPath method retrieves the location directly (//denotes any depth)
foreach ($xml->xpath ('//reply ') as $reply) {
echo $reply. '
';
}

(8) Traverse the message 1 all child nodes
Code Snippets
Children method to get all child nodes
foreach ($xml->msg->children () as $field) {
echo $field. '
';
}
(9) Reset message 1 release time
Code Snippets
Setting properties directly
$xml->msg->time = ' 2008-03-21 00:53:12 ';
(10) Set the ID property of reply 2
Code Snippets
Set the value of the managed array
$xml->msg->reply[1][' id '] = ' 222 ';
(11) Add a field that describes the author of the message
Code Snippets
Setting 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 ');
It should be possible to see how simple simplexml is!
3 Example: Data interaction between an XML file and a database
The following provides a relatively complete instance, the message information from the MySQL database query, save as a
An XML file as shown in the example above. Message and reply information are saved independently in two tables, using the MySQL function package
Can be implemented very simply as follows:

The code is as follows:
Copy CodeThe code is as follows:
Cong work atwed Mar 19:59:04 CST 2008
Saving data from the MySQL database to an XML file
The initial SimpleXMLElement object can be constructed in several ways:
1. Construct from DOM object
$dom = new DOMDocument ();
$dom->loadxml (" ");
$xml = Simplexml_import_dom ($dom);
2. Constructs from an XML file that contains only the root tag
$xml = simplexml_load_file (' Messages.xml ');
3, direct write root tag string construction
$xml = Simplexml_load_string (" ");
4. Constructor construction using the SimpleXMLElement class
$xml = new SimpleXMLElement (' ');
Connecting to a 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; Array index subscript for 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 its related reply information based on the message ID
$rsReply = mysql_query ("select * from replies where mid={$row [' ID ']}");
$j = 0; Index subscript for multi-line 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 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 it will report a fatal error that indicates:
Objects used as arrays in Post/pre increment/decrement must return values by reference. Hope everyone

Don't be fooled by this unintelligible hint. It is believed that the reader can write a code from an XML file to MySQL by reading the above code.

http://www.bkjia.com/PHPjc/321422.html www.bkjia.com true http://www.bkjia.com/PHPjc/321422.html techarticle 1 SimpleXML Introduction to work with XML files, there are two traditional ways of dealing with it: SAX and Dom. SAX is based on the event trigger mechanism, the XML file is scanned, the processing to be done ... .

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