Easily palate XML with php5

xiaoxiao2021-03-05  21

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

Hualian

Beijing Chang'an Street -9999 Chain Supermarket < CAT ID = "food"> food12 22.10 tel21 1290 carat31 112 < / Goods> Coat32 45 Hot41 99 file: Test.php

?

$ test = new simpledocumentParser (); $ test-> parse ("test.xml"); $ dom = $ test-> getSimpleDocument ();

Echo "

";

Echo "


"; echo "below is an array of entire XML data returned by a function getSavedata ()"; echo "
"; Print_R ($ DOM-> GetsaveData) ));

Echo "


"; echo "Below is the SETVALUE () function, add information to the root node, and then display the content of the result XML file"; echo "
$ DOM-> SetValue ("Telphone", "123456789); Echo Htmlspecialchars ($ DOM-> getsavexml ()); echo"
"; echo" below is GetNode () Function, returning information about all items under a class "; echo"
"; $ obj = $ dom-> getnode (" cat_food "); $ nodelist = $ obj-> getnode (); Foreach ($ data = $ node-> getValue (); echo " product name:". $ data [name]. "
"; Print_R ($ DATA); Print_R ($ Node-> getAttribute ());}

Echo "


"; echo "Below is the information"; echo "
"; $ obj = $ dom-> findnodebypath ("CAT_FOOD | Goods_food11); if (! is_Object ($ obj)) {echo" This item does not exist ";} else {$ data = $ obj-> getValue (); echo" product name : ". $ Data [name]."
"; Print_R ($ data); Print_R ($ OBJ-> GetAttribute ());}

Echo "


"; echo "below is the product /" food11 / "adding an attribute, then display the result"; echo "
"; $ OBJ = $ DOM-> FindNodebyPath (" cat_food | goods_food11); $ obj-> setvalue ("leaveword", array ("value" => "This product is good", "attrs" => array ("Author "=>" Hahawen "," Date "=> DATE ('YM-D')))))); Echo Htmlspecialchars ($ DOM-> GetsaveXML ());

Echo "


"; echo "Below is the REMOVALUE () / removettribute () function, give the product /" food11 / "change the property, then display the result"; echo "< / font>
"; $ OBJ = $ DOM-> FindNodebyPath (" Cat_food | Goods_food12 "); $ OBJ-> SetValue (" Name "," New Food12 "); $ OBJ-> RemoveValue (" DESC ") Echo htmlspecialchars ($ DOM-> getSavexml ()); echo "
"; echo "below is through the CreateNode () function, add goods, then display the result"; echo "< / font>
"; $ OBJ = $ DOM-> FindNodebyPath (" cat_food "); $ newobj = $ obj-> createnode (" Goods ", array (" id "=>" food13)); $ newobj -> SetValue ("Name", "Food13"); $ newobj-> setValue ("Price", 100); Echo Htmlspecialchars ($ DOM-> GetSavexml ());

Echo "


"; echo "Below is the removing product, then delete the item, then display the result"; echo "
"; $ OBJ = $ DOM -> FindnodebyPath; $ OBJ-> RemoveNode ("Goods_food12"); Echo Htmlspecialchars ($ DOM-> GetSavexml ());

?>

File: SimpleDocumentParser.php

* @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

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 / r / n";

}

Foreach ($ this-> getnode () as $ node) $ STR. = $ node-> getsavexml ($ level 1). "/ r / n";

$ Str. = "$ prefixspace nodetag>";

Return $ Str;}

Function __destruct () {unset ($ this-> Nodes, $ this-> attributes, $ this-> values);

}

}?>

Document: SimpleDocumentroot.php

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

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.

Hualian

Beijing Chang'an Street -9999 Chain Supermarket < Telphone> 123456789 food12 22.10 > Good things recommended tel21 1290 Coat32 45 Hot41 99 The following is the information of all items under a classification by getnode () functions.

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

Hualian

Beijing Chang'an Street -9999 Chain Supermarket < Telphone> 123456789 food11 12.90 food12 22.10 = "Hahawen> Things recommend tel21 1290 < Cat ID = "coat"> Coat31 112 Hot41 99

Below is the REMOVALUE () / RemoveAttribute () function, to the product "Food11" changes and delete the properties, then display the result after the operation

Hualian

Beijing Chang'an Street -9999 Chain Supermarket < Telphone> 123456789 food11 12.90 new food12 22.10 tel21 1290 Coat31 112 carat32 45 < / cat> Hot41 99 below is through the CREATENODE () function, Add goods, then display the resulting result

Hualian

Beijing Chang'an Street -9999 Chain Supermarket < Telphone> 123456789 food11 12.90 new food12 22.10 tel21 1290 Coat31 112 < Goods id = "coat32"> coat32 45 Hot41 99 The following is through the removenode () function, delete the item, then display the result after deletion

转载请注明原文地址:https://www.9cbs.com/read-32142.html

New Post(0)