Use SimpleXML to process XML files under PHP_PHP Tutorial
WBOY
Release: 2016-07-21 15:40:00
Original
861 people have browsed it
1 Introduction to SimpleXML To process XML files, there are two traditional processing ideas: SAX and DOM. SAX is based on an event triggering mechanism. scans the XML file once to complete the processing; DOM constructs the entire XML file into a DOM tree, and completes the processing by traversing the DOM tree. Both methods have their own advantages and disadvantages. SAX's processing idea is relatively abstract, and DOM's processing process is relatively cumbersome, making them neither very suitable for beginners to get started. PHP5 introduces a new set of XML processing functions, namely SimpleXML. As the name suggests, SimpleXML itself is small and compact, and only provides a few methods and functions. However, it is very powerful for processing XML files and the operation is very simple. First of all, it provides simple functions to directly construct SimpleXMLElement objects from XML documents, strings, or DOM objects; secondly, SimpleXMLElement provides simple methods to construct attributes and subsections , and XPath operations; however, the simplest thing about SimpleXML is that it provides methods for node operations using standard object attributes and object iterators. This processing idea makes it possible to use PHP to process XML documents. A huge simplification.
2 SimpleXML Getting Started Example Below we use some small code snippets to understand a little about the power and simplicity of SimpleXML. For the convenience of example, We use a Messages.xml file, which contains this XML code: Messages.xml
Copy code The code is as follows :
This is Title Here is Content
< ;reply id='11'>reply 1 reply 2
This is an XML document that saves message information. Each message includes attribute id, sub-nodes title, content, time and several reply messages to it. Each reply includes attribute id and reply. content. The process and method of using SimpleXML to process and output the content of this XML document are as follows. (1) Construct SimpleXMLElement object
Code snippet $xml = simplexml_load_file('Messages.xml'); If this xml 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 //can be used Access child nodes through attributes, and you can directly get the content of the node through the node's label name echo $xml->msg->title; (3) Output the first reply message of message 1 Code snippet //Multiple nodes with the same name at the same level automatically become arrays, and their contents can be accessed through index subscripts echo $xml->msg->reply[0]; (4 ) Output the id of the message Code snippet //The attributes and values of the node are encapsulated into the keys and values of the associative array echo $xml->msg['id']; (5 ) Output the id of the second reply Code snippet //Become 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 ids of all replies in sequence Code snippets //Use foreach to traverse the node with the same name foreach ($xml->msg-> reply as $reply){ echo $reply['id']; } (7) Use XPath to retrieve all reply information Code snippet //xpath method to directly retrieve the location (// represents any depth) foreach ($xml->xpath('//reply') as $reply){ echo $reply.' '; }
(8) Traverse all child nodes of message 1 Code snippet //children method to get all child nodes foreach ($xml->msg->children() as $field ){ echo $field.' '; } (9) Reset the publishing time of message 1 Code snippet //Set attributes directly $ xml->msg->time = '2008-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'] = '222'; (11) Add a field describing the message author Code snippet // Directly set the attribute $xml->msg->author = 'zhangsan'; (12) Save the author of the message as an attribute Code snippet //Set the key of the associative array $xml->msg['author'] = 'zhangsan'; (13) Resave the object to the file Code snippet //Save $xml->asXML( 'MessagesNew.xml'); You should be able to see how simple SimpleXML is! 3 Example: Data interaction between XML files and databases A relatively complete example is provided below to query the message information from the MySQL database and save it as an XML file as shown in the above example. . Message information and reply information are stored independently in two tables. Using the MySQL function package can be very simply implemented as follows:
The code is as follows:
Copy codeThe code is as follows:
//cong work atWed Mar 20 19:59:04 CST 2008 //Save data from MySQL database to XML file //Can be used Construct the initial SimpleXMLElement object in the following ways //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. Write the root tag string structure directly //$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 messages $rs = mysql_query("select * from messages"); $i = 0; //Used as 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 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 about the above code is the line marked ①. When we want to add a new node or attribute to a SimpleXML object, we must ensure that its parent node exists, otherwise a fatal error will be reported. The prompt message is: Objects used as arrays in post/ pre increment/decrement must return values by reference. I hope everyone
will not be confused by this unintelligible reminder. I believe that readers can write a code from XML file to MySQL by understanding the above code.
http://www.bkjia.com/PHPjc/321422.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321422.htmlTechArticle1 Introduction to SimpleXML To process XML files, there are two traditional processing ideas: SAX and DOM. Based on the event triggering mechanism, SAX scans the XML file once and completes the processing;...
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn