When using the SAX method, you must build 3 functions yourself, and use these three functions to return data and require stronger logic. When processing XML of different structures, it is also necessary to re-construct these three functions, trouble!
With the DOM mode, it is better, but he regards each node as a node, you should write a lot of code, trouble!
There are a lot of open source XML parses for the online source. I have seen a few, but my heart always feels not practical, I feel that I always follow the buttocks of others.
In these few days, I was very tired, so I decided to change my head, write some PHP code. In order to prevent the XML parsing process, I spent a day, I spent a day, I wrote the following XML parsing class, then With the following things.
The implementation is achieved by packaging "resolution results" in SAX mode. Overall, for my individual, it is also very practical, performance can also, basically complete most of the processing requirements.
Function: 1 / Query / Add / Modify / Remove the Basic XML file nodes. 2 / Export all the data of the XML file into an array. 3 / The entire design uses an OO method, when the operation result set, how to use is similar to the DOM
Disadvantages: 1 / Each node is best with an ID (see later example), each "node name" = "tag _ node ID", if this ID value is not set, the program will automatically give him Generate an ID, this ID is the position number of this node in his superior node, starting from 0. 2 / Query a node can be done by connecting "Node Node" with "|" symbol. These "node names" are the names of the superior nodes written in sequence.
Instructions for use: Run the following example, you can see the instructions of the function on the execution result page
The code is implemented by PHP5, and it is not possible to run in PHP4.
Since I just finished, I didn't organize the document. The following example demonstrates only part of the function, the code is not very difficult, if you want to know more features, you can study the research source code.
Directory Structure:
Test.php test.xml xml / simpledocumentbase.php xml / simpledocumentroot.php XML / SimpleDocumentParser.php
Document: Test.xml
XML Version = "1.0" Encoding = "GB2312"?>
? $ test = new simpledocumentParser (); $ test-> parse ("test.xml"); $ dom = $ test-> getSimpleDocument (); Echo "";
Echo "
Echo "
Echo "
Echo "
Echo "
Echo "
?>
File: SimpleDocumentParser.php
php / ** * ================================================================================================================================================================================= ===== * * @Author Hahawen (older youth)
* @since 2004-12-04 * @copyright copyright (c) 2004, nxcoder group * * ============================= =================== * / / / ** * Class SimpleDocumentParser * Use Sax Parse XML File, And Build SimpleDocumentObject * All this Pachage's Is Work for XML File, And Method IS Action as Dom. * * @package smartweb.common.xml * @version 1.0 * / class simpeter.com {private $ domrootobject = null Download Adobe Reader Download Adobe Reader DOMROTOBJECT = NULL;
Private $ currentno = null; private $ currentname = null; private $ currentValue = null; private $ currentattribute = null;
Public function getSimpledocument () {Return $ this-> domrootobject;}
public function parse ($ file) {$ xmlParser = xml_parser_create (); xml_parser_set_option ($ xmlParser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option ($ xmlParser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option ($ xmlParser, XML_OPTION_TARGET_ENCODING, 'UTF-8'); xml_set_object ($ XMLPARSER, $ THIS);
XML_SET_EEMENT_HANDLER ($ XMLPARSER, "StartElement", "endelement"); XML_SET_CHARACTER_DATA_HANDLER ($ XMLParser, "CharacterData");
IF (! XML_PARSE ($ XMLPARSER, File_Get_Contents ($ file)))
DIE (Sprintf ("XML Error:% S at line% D", XML_ERROR_STRING (XML_GET_ERROR_CODE ($ xmlparser), XML_GET_CURRENT_LINE_NUMBER ($ XMLParser)))
XML_Parser_Free ($ XMLPARSER);
}
private function startElement ($ parser, $ name, $ attrs) {$ this-> currentName = $ name; $ this-> currentAttribute = $ attrs; if ($ this-> currentNO == null) {$ this-> domRootObject = New SimpleDocumentroot ($ this-> currentno = $ this-> domrootobject;} else {$ this-> currentno = $ this-> currentno-> createnode ($ Name, $ attrs);
}
Private Function endelement ($ Parser, $ Name) {ified ($ this-> currentname == $ name)
{$ Tag = $ this-> currentno-> getseq (); $ this-> currentno = $ this-> currentno-> getpnodeObject (); if ($ this-> currentattribute! = Null && sizeof ($ this-> CurrentAttRibute) )> 0) $ this-> currentno-> setValue ($ name, array ('value' => $ this-> currentValue, 'attrs' => $ this-> currentattribute)); Else $ this-> currentno-> SetValue ($ Name, $ this-> CurrentValue);
$ this-> currentno-> removenode ($ tag);} else {$ this-> currentno = (is_a ($ this-> currentno, 'simpledocumentroot'))? Null: $ this-> currentno-> getpnodeObject (); }
Private Function CharacterData ($ Parser, $ DATA) {$ this-> CurrentValue = ICONV ('UTF-8', 'GB2312', $ DATA);
Function __destruct () {unset ($ this-> domrootobile);
}?>
File: SimpleDocumentBase.php
php / ** * ================================================================================================================================================================================= ====== * @Author Hahawen (Uld Youth) * @since 2004-12-04 * @copyright CopyRight (C) 2004, NxCoder Group * * ============== ===================================================== *** * Abstract class simpledocumentbase * base class for XML file PARSE * All this Pachage's IS Work for XML File, And Method Is Action As Dom. * * 1 / Add / Update / Remove Data OF XML File. * 2 / Expode Data TO Array. * 3 / Rebuild XML file * * @package Smartweb.common.xml * @abstract * @version 1.0 * / Abstract Class SimpleDocumentBase {Private $ Nodetag = NULL;
Private $ attributes = array (); private $ values = array ();
Private $ nodes = array ();
Function __construct ($ nodetag) {$ this-> nodetag = $ nodetag;
Public function getnodetag () {return $ this-> nodetag;
Public Function SetValues ($ VALUES) {$ this-> VALUES = $ values;}
Public Function SetValue ($ name, $ value) {$ this-> values [$ name] = $ value;}
Public Function getValue ($ name = null) {return $ name == null? $ this-> Values: $ this-> values [$ name];}
Public Function RemoveValue ($ name) {unset ($ this-> Values ["$ name"]);}
Public Function SetAttributes ($ this-> attributes = $ attributes;} public function sets; $ this-> attributes [$ name] = $ value;}
Public Function GetAttribute ($ name = null) {return $ name == Null? $ this-> attributes: $ this-> attributes [$ name];}
Public Function Removettribute ($ name) {unset ($ this-> attributes ["$ name"]);}
Public function getNodesize () {Return Sizeof ($ this-> nodes);
Protected Function SetNode ($ this-> nodes [$ name] = $ nodeId;
Public Abstract Function Createnode ($ Name, $ Attributes);
Public Abstract Function RemoveNode ($ Name);
Public Abstract Function GetNode ($ Name = NULL);
Protected function getnodeid ($ name = null) {Return $ name == Null? $ this-> nodes: $ this-> nodes [$ name];}
protected function createNodeByName ($ rootNodeObj, $ name, $ attributes, $ pId) {$ tmpObject = $ rootNodeObj-> createNodeObject ($ pId, $ name, $ attributes);? $ key = isset ($ attributes [id]) $ name .'_ '. $ attributes [ID]: $ name.'_'. $ this-> getnodesize (); $ this-> setnode ($ key, $ tmpObject-> getseq ()); return $ tmpObject;}
protected function removeNodeByName ($ rootNodeObj, $ name) {$ rootNodeObj-> removeNodeById ($ this-> getNodeId ($ name)); if (sizeof ($ this-> nodes) == 1) $ this-> nodes = array ( ); Else Unset ($ this-> nodes [$ name]);
Protected Function GetNodebyName ($ Rootnodeobj, $ Name = NULL) {IF ($ Name == Null) {$ TMPLIST = Array (); $ TMPIDS = $ THIS-> GetNodeId (); Foreach ($ TMPIDS AS $ Key => $ ID) $ TMPLIST [$ key] = $ rootnodeObj-> getnodebyid ($ ID); Return $ TMPLIST;} else {$ ID = $ this-> getNodeId ($ name); if ($ ID === null) {$ Tmpids = $ this-> getnodeid (); foreach ($ TMPIDS AS $ TKEY => $ TID) {IF ($ key, $ name) == 0) {$ ID = $ TID; Break;}}} return $ rootnodeobj-> getnodebyid ($ ID);}}
Public Function FindnodebyPath ($ PATH) {$ POS = STRPOS ($ PATH, '|'); if ($ POS <= 0) {Return $ this-> GetNode ($ PATH);
} Else {
$ tmpobj = $ this-> getnode (Substr ($ PATH, 0, $ POS);
Return is_Object ($ Tmpobj)? $ TMPOBJ-> FindNodebyPath (Substr ($ PATH, $ POS 1): null;}}
Public function getsavedata () {$ data = $ THIS-> VALUES; IF ($ this-> attributes> 0)
$ data [attrs] = $ this-> attributes; $ nodelist = $ this-> getNode ();
IF ($ nodelist == null)
Return $ Data; Foreach ($ Nodelist As $ Key => $ Node) {$ data [$ key] = $ node-> getsavedata ();
Return $ data;}
Public Function GetSavexml ($ level = 0) {$ prefixSpace = STR_PAD ("", $ level, "/ t"); $ str = "$ prefixspace <$ this-> nodetag";
Foreach ($ THIS-> Attributes as $ key => $ value) $ STR. = "$ key = /" $ value / "";
$ Str. = "> / r / n";
Foreach ($ this-> Values as $ key => $ value) {
IF (is_ARRAY) {$ Str. = "$ PrefixSpace / T <$ key";
Foreach ($ value [attrs] as $ attkey => $ attvalue)
$ Str. = "$ attkey = /" $ attvalue / "";
$ TMPSTR = $ VALUE [Value];
Else
{$ Str. = "$ PrefixSpace / T <$ key";
$ tmpstr = $ value;} $ tmpstr = trim (TRIM ($ Tmpstr, "/ R / N");
$ Str. = ($ tmpstr === NULL || $ tmpstr === "")? "/> / r / n": "> $ TMPSTR $ key> / r / n";
}
Foreach ($ this-> getnode () as $ node) $ STR. = $ node-> getsavexml ($ level 1). "/ r / n";
$ Str. = "$ prefixspace $ this-> nodetag>";
Return $ Str;}
Function __destruct () {unset ($ this-> Nodes, $ this-> attributes, $ this-> values);
}
}?>
Document: SimpleDocumentroot.php
php / ** * ================================================================================================================================================================================= === * * @Author hahawen * @since 2004-12-04 * @copyright copyright (c) 2004, nxcoder group * * ================= ============================================================================================================================================================= all this pachage's is work for xml file, and method is action as DOM * * @package SmartWeb.common.xml * @version 1.0 * / class SimpleDocumentRoot extends SimpleDocumentBase {private $ prefixStr = '';. private $ nodeLists = array () ;
Function __construct ($ nodetag) {parent :: __ construct ($ nodetag);
public function createNodeObject ($ pNodeId, $ name, $ attributes) {$ seq = sizeof ($ this-> nodeLists); $ tmpObject = new SimpleDocumentNode ($ this, $ pNodeId, $ name, $ seq); $ tmpObject-> setAttributes ($ attributes);
$ this-> nodelists [$ seq] = $ tmpObject; return $ tmpObject;}
Public Function Removenodebyid ($ ID) {IF (Sizeof ($ this-> nodelists) == 1) $ this-> nodelists = array (); else unset ($ this-> nodelists [$ ID]);}
Public Function GetNodeByid ($ ID) {Return $ this-> Nodelists [$ ID];
public function createNode ($ name, $ attributes) {return $ this-> createNodeByName ($ this, $ name, $ attributes, -1);} public function removeNode ($ name) {return $ this-> removeNodeByName ($ this, $ Name);
Public Function GetNode ($ name = null) {Return $ this-> GetNodeByName ($ this, $ name);}
Public Function GetSavexml () {$ prefixspace = ""; $ str = $ this-> prefixstr. "/ r / n"; return $ str.parent :: getsavexml (0);}}?>
Document: SimpleDocumentNode.php
php / ** * ================================================================================================================================================================================= ==== * * @Author Hahawen * @since 2004-12-04 * @copyright copyright (c) 2004, nxcoder group * * ================ ===================================================================== . * all this pachage's is work for xml file, and method is action as DOM * * @package SmartWeb.common.xml * @version 1.0 * / class SimpleDocumentNode extends SimpleDocumentBase {private $ seq = null;. private $ rootObject = null; Private $ pnodeid = NULL;
function __construct ($ rootObject, $ pNodeId, $ nodeTag, $ seq) {parent :: __ construct ($ nodeTag); $ this-> rootObject = $ rootObject; $ this-> pNodeId = $ pNodeId; $ this-> seq = $ Seq;} public function getPnodeObject () {return ($ this-> pnodeid == - 1)? $ this-> rootobject: $ this-> rootobject-> getnodebyid ($ this-> pnodeid);}
Public function getseq () {return $ this-> seq;}
Public Function Createnode ($ Name, $ Attributes) {Return $ this-> CreatenodebyName ($ this-> Rootobject, $ Name, $ Attributes, $ this-> getseq ());}
Public Function Removenode ($ Name) {Return $ this-> RemovenodebyName ($ this-> rootobject, $ name);}
Public Function GetNode ($ Name = null) {Return $ this-> getnodebyname ($ this-> rootobject, $ name);}}?>
The following is an example run pair
Below is an array of the entire XML data returned by the function getsavedata ()
Array ([Name] => Hualian [Address] => Beijing Chang'an Street -9999 [DESC] => Chain Supermarket [CAT_FOOD] => Array ([Attrs] => Array ([id] => food) [Goods_food11 ] => Array ([Name] => Food11 [price] => 12.90 [attrs] => array ([ID] => food11) [Goods_food12] => array ([name] => Food12 [price] => 22.10 [desc] => Array ([value] => Good things recommended [attrs] => array ([creator] => Hahawen) [attack] => array ([id] => food12 )) [CAT_1] => Array ([Goods_tel21] => Array ([Name] => tel21 [price] => 1290 [attrs] => array ([ID] => tel21)) [CAT_COAT] => Array ([attrs] => array ([ID] => coat) [Goods_Coat31] =>
Array ([Name] => Coat31 [Price] => 112 [attrs] => array ([ID] => Coat31) [Goods_Coat32] => Array ([Name] => Coat32 [Price] => 45 [Attrs ] => Array ([ID] => Coat32))) [Special_hot] => Array ([attt] => array ([ID] => Hot) [Goods_0] => Array ([Name] => Hot41 [Price ] => 99))) The following is to add information to the root node by the setValue () function, and the content of the XML file is displayed later.
XML Version = "1.0" Encoding = "GB2312"?>
Product Name: Food11Array ([Name] => Food11 [Price] => 12.90) Array ([ID] => Food11) Product Name: Food12Array ([Name] => Food12 [Price] => 22.10 [Desc] => Array ([Value] => Good things recommended [attrs] => array ([creator] => Hahawen)) Array ([ID] => Food12)
Below is the information of a product through the FINDNODEBYPATH () function.
Product Name: Food11Array ([Name] => Food11 [Price] => 12.90) Array ([ID] => FOOD11) The following is through the setValue () function, add the property to the product "Food11", then display the resulting result
XML Version = "1.0" Encoding = "GB2312"?>
Below is the REMOVALUE () / RemoveAttribute () function, to the product "Food11" changes and delete the properties, then display the result after the operation
XML Version = "1.0" Encoding = "GB2312"?>
XML Version = "1.0" Encoding = "GB2312"?>