Complete PHP-encapsulated XML simple operation class instance, and php-encapsulated xml instance

Source: Internet
Author: User

Complete PHP-encapsulated XML simple operation class instance, and php-encapsulated xml instance

This example describes the simple XML operation class encapsulated by PHP. We will share this with you for your reference. The details are as follows:

Xml_dom.php encapsulation class file:

<? Php/*** Class xml_dom * nodeType: 1 XML_ELEMENT_NODE: attributes storage node attribute list (read-only) childNodes storage node subnode list (read-only) dataType returns the Data Type of this node Definition defines (read-only) nodes in DTD or XML mode. Doctype specifies the document type node (read-only). documentElement returns the root element (read/write) of the document) firstChild returns the first subnode (read-only) Implementation of the current node. The XMLDOMImplementation object lastChild returns the last subnode (read-only) nextSibling of the current node to the next sibling node (read-only) of the current node) nodeName return node name (read-only) nodeType return node type (read-only) nodeTypedValue storage node value (read/write) nodeValue return node text (read/write) ownerDocument returns the root file (read-only) containing this node. parentNode returns the parent node (read-only). Parsed returns whether the node and its child nodes have been resolved (read-only). Prefix returns the namespace Prefix (read-only) preserveWhi TeSpace specifies whether to retain white space (read/write) previussibling returns the previous sibling node (read-only) Text of this node to the Text content of this node and its descendants (read/write) the url returns the URL (read-only) XML of the recently loaded Xml document and the XML Representation (read-only) of the node and its descendants. The appendChild adds a new subnode to the current node, after the last sub-node is placed, cloneNode returns the copy of the current node. createAttribute creates a new attribute. createCDATASection creates a CDATA segment including the given data. createComment creates a comment node. createDocumentFragment creates a DocumentFragment object. createElement creates an element create an EntityReference object createNode to create a given type, name and namespace node create PorcessingInstruction create operation command node createTextNode create text node getElementsByTagName returns hasChildNodes of the specified name element set to return whether the current node has a subnode insertBefore Insert the subnode Load before the specified node import the specified location XML document loadXML import the XML document of the specified string removeChild from the child node list delete the specified child node replaceChild from the child node list Replace the specified child node Save the XML file to the specified node selectNodes on the node specified match, return the matched node list selectSingleNode to match the specified node, return the first matched node transformNode to convert the node and its descendants using the specified style table. **/class xml_dom {protected $ dblink; // xml connection Protected $ dbfile; // xml file path/*** xml file construction class * @ param $ db_file xml file */public function _ construct ($ db_file) {$ this-> dbfile = $ db_file; if (! File_exists ($ db_file) {// die ('database file not found '); $ this-> dblink = new DOMDocument ('1. 0 ', 'utf-8'); $ root = $ this-> dblink-> createElement ('root'); $ this-> dblink-> appendChild ($ root ); $ this-> dblink-> formatOutput = true; // retain the indent style for the xml file $ this-> dblink-> save ($ this-> dbfile );} else {$ this-> dblink = new DOMDocument (); $ this-> dblink-> formatOutput = true; $ this-> dblink-> load ($ this-> dbfile) ;}/ *** traverse all elements * ==== ========================================================== = * Standard xml file, an element may have n attributes. You can use the custom key [nodevalue] to obtain the element value * <? Xml version = "1.0" encoding = "UTF-8"?> * <Table name = "posts"> * <column name = "id"> 1 </column> * <column name = "title"> title 1 </column> * <column name = "content"> content 1 </column> * </table> * ====================== ===========================* simple xml file, no attribute. Key values correspond to each other. * <? Xml version = "1.0" encoding = "UTF-8"?> * <Root> * <posts> * <id> 1 </id> * <title> title 1 </title> * <content> details 1 </content> * </posts> * </root> * @ param $ node * @ return array */function getData ($ node = 0) {if (! $ Node) {$ node = $ this-> dblink-> documentElement;} $ array = array (); foreach ($ node-> attributes as $ attribute) {$ key = $ attribute-> nodeName; $ val = $ attribute-> nodeValue; $ array [$ key] = $ val;} if (count ($ array )) // if there is an attribute, the [nodevalue] key is used to represent the value {$ array ['nodevalue'] = $ node-> nodevalue ;} // recursively traverse all child elements $ node_child = $ node-> firstChild; while ($ node_child) {if (XML_ELEMENT_NODE = $ node_child-> nodeType) {$ tagn Ame = $ node_child-> tagName; $ result = $ this-> getData ($ node_child); if (isset ($ array [$ tagname]) // The child element with duplicate tagnames is found to exist. Therefore, use an array to store all the child elements with duplicate tagnames {if (! Is_array ($ array [$ tagname] [0]) {$ tmp = $ array [$ tagname]; $ array [$ tagname] = array (); $ array [$ tagname] [] = $ tmp;} $ array [$ tagname] [] = $ result;} else {$ array [$ tagname] = $ result ;}} $ node_child = $ node_child-> nextSibling;} if (! Count ($ array) // returns the nodeValue {return $ node-> nodeValue;} return $ array;} if no child element exists & No attribute = the last child element ;} /*** write array data to an xml file (overwrite) * @ param $ data */public function setData ($ data, & $ node = 0) {$ is_root = false; if (! $ Node) {$ is_root = true; $ node = $ this-> dblink-> documentElement; // clear the original data $ remove = array (); $ node_child = $ node-> firstChild; while ($ node_child) {$ remove [] = $ node_child; $ node_child = $ node_child-> nextSibling ;} foreach ($ remove as $ r) {$ node-> removeChild ($ r) ;}} if (is_array ($ data )) {foreach ($ data as $ k =>$ v) {if (is_array ($ v) {foreach ($ v as $ r) {$ item = $ this-> dblink-> createElement ($ k); $ result = $ this-> setData ($ r, $ item ); $ node-> appendChild ($ result) ;}} else {$ item =$ this-> dblink-> createElement ($ k ); $ value = $ this-> dblink-> createTextNode ($ v); $ item-> appendChild ($ value); $ node-> appendChild ($ item );}}} else {$ item = $ this-> dblink-> createTextNode ($ data); $ node-> appendChild ($ item);} if ($ is_root) {$ this-> dblink-> save ($ this-> dbfile); // overwrite} else {return $ node ;}}}

An example is as follows:

Smp. xml file:

<? Xml version = "1.0" encoding = "UTF-8"?> <Root> <posts> <id> 1 </id> <title> title 1 </title> <content> details 1 </content> </posts> <posts> <id> 2 </id> <title> title 2 </title> <content> content 2 </content> </posts> <id> 3 </ id> <title> title 3 </title> <content> details 3 </content> </posts> </root>

Index. php file:

Include ("xml_dom.php"); $ xml = new xml_dom ("smp. xml "); // load the xml file $ xmlarr = $ xml-> getData (); // read the content of the xml file var_dump ($ xmlarr );

Running result:

Array (1) {["posts"] => array (3) {[0] => array (3) {["id"] => string (1) "1" ["title"] => string (9) "title 1" ["content"] => string (15) "details 1"} [1] => array (3) {["id"] => string (1) "2" ["title"] => string (9) "title 2" ["content"] => string (15) "details 2"} [2] => array (3) {["id"] => string (1) "3" ["title"] => string (9) "title 3" ["content"] => string (15) "details 3 "}}}

PS: Here are some online tools for xml operations for your reference:

Online XML/JSON conversion tools:
Http://tools.jb51.net/code/xmljson

Online formatting XML/online compression XML:
Http://tools.jb51.net/code/xmlformat

XMLOnline compression/formatting tools:
Http://tools.jb51.net/code/xml_format_compress

XMLCode Online formatting and beautification tools:
Http://tools.jb51.net/code/xmlcodeformat

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.