Easily palate XML with php5

xiaoxiao2021-03-06  64

Article source http://blog.9cbs.net/hahawen, please indicate the source, thank you

When using SAX, you must build 3 functions yourself, and use these three functions to return data, require strong logic. When processing XML of different structures, it is necessary to re-construct these three functions. trouble!

With the DOM mode, it is better, but he regards each node as a node, to operate 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 the "resolution of SAX mode". In general, for my personal, performance is also possible, basically can complete most of the processing requirements.

Function: 1 / Query / Add / Modify / Delete Work. 2 / Export All Data of the XML file into an array .3 / The entire design uses the OO method, when the results set, How to use Similar to 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 / SimpleDocumentNode.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

require_once "xml / SimpleDocumentParser.php"; require_once "xml / SimpleDocumentBase.php"; require_once "xml / SimpleDocumentRoot.php"; require_once "xml / SimpleDocumentNode.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

/ **

* =========================================================================================================================================================================================== =========

*

* @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 WORK for XML File, And Method Is Action As Dom.

*

* @package smartweb.common.xml

* @version 1.0

* /

Class SimpleDocumentParser

{

Private $ domrootobject = null;

Private $ currentno = NULL;

Private $ currentname = null;

PRIVATE $ CURRENTVALUE = NULL;

PRIVATE $ CURRENTATTRIBUTE = NULL;

Public function getSimpleDocument ()

{

Return $ this-> DOMROTOBJECT;

}

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_ELEMENT_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 ($ name);

$ this-> currentno = $ this-> domrootobject;}

Else

{

$ this-> currentno = $ this-> currentno-> createnode ($ name, $ attrs);

}

}

Private function endelement ($ Parser, $ Name)

{

IF ($ this-> currentname == $ name)

{

$ SEQ = $ this-> currentno-> getseq ();

$ this-> currentno = $ this-> currentno-> getpnodeObject ();

$ tag = $ this-> currentno-> getnodename ($ SEQ);

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

/ **

* =========================================================================================================================================================================================== =========

*

* @Author Hahawen (older youth)

* @since 2004-12-04

* @copyright Copyright (C) 2004, NxCoder Group

*

* =========================================================================================================================================================================================== ========= * /

/ **

* Abstract Class SimpleDocumentBase

* Base Class for XML File Parse

* All this PACHAGE'S WORK for XML File, And Method Is Action As Dom.

*

* 1 / add / update / remove data of xml file.

* 2 / Explode 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-> value = $ values;

}

Public Function SetValue ($ Name, $ Value)

{

$ this-> values ​​[$ name] = $ value;

}

Public Function GetValue ($ name = null)

{

Return $ name == Null? $ this-> VALUES: $ this-> value [$ name];

}

Public Function RemoveValue ($ NAME)

{

Unset ($ this-> VALUES ["$ name"]);

}

Public Function SetAttributes ($ attributes) {

$ this-> attributes = $ attribute;

}

Public Function SetAttribute ($ Name, $ VALUE)

{

$ 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 ($ Name, $ NodeID)

{

$ 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];

}

Public Function GetNodeName ($ ID) {$ TMP = Array_flip ($ this-> nodes); Return $ TMP [$ ID];

Protected Function CreatenodebyName ($ Name, $ Attributes, $ PID)

{

$ tmpObject = $ rootnodeobj-> CreatenodeObject ($ PID, $ Name, $ Attributes);

$ key = isset ($ attributes [id])? $ name.'_ '. $ attributes [id]: $ name.'_'. $ this-> getNodESSIZE ();

$ 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 (STRPOS ($ 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 (SizeOf ($ 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

/ **

* =========================================================================================================================================================================================== ======== *

* @Author Hahawen (older youth)

* @since 2004-12-04

* @copyright Copyright (C) 2004, NxCoder Group

*

* =========================================================================================================================================================================================== =========

* /

/ **

* Class SimpleDocumentroot

* XML Root Class, include Values ​​/ Attributes / Subnodes.

* All this PACHAGE'S 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

/ **

* =========================================================================================================================================================================================== =========

*

* @Author Hahawen (older youth)

* @since 2004-12-04

* @copyright Copyright (C) 2004, NxCoder Group

*

* =========================================================================================================================================================================================== =========

* /

/ **

* Class SimpleDocumentNode

* XML Node Class, Include Values ​​/ Attributes / Subnodes.

* All this PACHAGE'S 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

)

)

[attrs] => 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

[p => 45

[attrs] => array

(

[ID] => Coat32

)

)

)

[special_hot] => array

[attrs] => array

(

[ID] => HOT

)

[Goods_0] => Array

(

[name] => Hot41

[Price] => 99

)

)

)

Below is the setValue () function, add information to the root node, and then display the contents of the XML file after adding

Hualian

Beijing Chang'an Street -9999

Chain Supermarket

123456789

Food11

12.90

Food12

22.10

Good things recommended

Tel21

1290

Coat31

112

Coat32

45

hot41

99

Below is through the getNode () function, return information for all items under a classification.

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

)

Below is the SETVALUE () function, add the property to the product "Food11", then display the added result

Hualian

Beijing Chang'an Street -9999

Chain Supermarket

123456789

Food11

12.90

This product is good

Food12

22.10

Good things recommended

Tel21

1290

Coat31

112

Coat32

45

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

123456789

Food11

12.90

This product is good

new food12

22.10

Tel21

1290

Coat31

112

Coat32

45

hot41

99

Below is the result of adding items through the CreateNode () function, then display the resulting result

Hualian

Beijing Chang'an Street -9999

Chain Supermarket

123456789

Food11

12.90

This product is good

new food12 22.10

food13

100

Tel21

1290

Coat31

112

Coat32

45

hot41

99

Below is the RemoveNode () function, delete the item, then display the result after deletion

Hualian

Beijing Chang'an Street -9999

Chain Supermarket

123456789

Food11

12.90

This product is good

food13

100

Tel21

1290

Coat31

112

Coat32

45

hot41

99

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

New Post(0)