Custom php class (Search/modify) xml document
Last Update:2018-12-08
Source: Internet
Author: User
I recently watched the PHP tutorial video, where I talked about the xml file for PHP operations and learned some DOMDocument classes. I can't quite understand the manual. However, I wrote a class to find the xml node and modify the node value. The background is explained and the code is as follows:
Copy code The Code is as follows :/*
<? Xml version = "1.0" encoding = "UTF-8"?>
<Class>
<Student number = "101">
<Name> Sun Wukong </Name>
<Name> sun Walker </Name>
<Age> monkey precision </age>
<Introduction> </introduction>
</Student>
<Student number = "102">
<Name> White Bone essence </Name>
<Age> 140 </age>
<Introduction> thousands of magic changes </introduction>
</Student>
<Student number = "103">
<Name> </Name>
<Name> failed pig </Name>
<Age> 200 </age>
<Introduction> sleeping </introduction>
</Student>
</Class>
*/
Class xmlDom {
Public $ version;
Public $ encoding;
Private $ xml;
Private $ items;
Private $ seachNode = '';
Private $ seachItem = '';
Private $ seachValue = '';
Public $ writeBytes = 0;
Function _ construct ($ xmlFile = '', $ version = '1. 0', $ encoding = 'utf-8 '){
$ This-> version = $ version;
$ This-> encoding = $ encoding;
$ This-> xml = new DOMDocument ($ version, $ encoding );
If ($ xmlFile) $ this-> xml-> load ($ xmlFile );
}
Function getRootEle ($ rootTag ){
$ This-> xmlRoot = $ this-> xml-> getElementsByTagName ($ rootTag)-> item (0 );
}
Function getSeachItem ($ itemsTag, $ seachNode, $ seachValue ){
$ This-> items = $ this-> xml-> getElementsByTagName ($ itemsTag );
$ This-> items-> length;
For ($ I = 0; $ I <$ this-> items-> length; $ I ++ ){
$ Item = $ this-> items-> item ($ I); // Element
$ Node = $ item-> getElementsByTagName ($ seachNode); // node
For ($ j = 0; $ j <$ node-> length; $ j ++ ){
$ SubNode = $ node-> item ($ j );
If ($ seachValue = $ subNode-> nodeValue ){
$ This-> seachNode = $ subNode;
$ This-> seachItem = $ item;
$ This-> seachValue = $ subNode-> nodeValue;
Break (2 );
}
}
}
Return ($ this-> seachNode )? True: false;
}
Function update ($ nodeValue, $ nodeTag = '', $ append = false, $ index = 0 ){
If ($ append ){
If ($ nodeTag)
$ This-> seachItem-> getElementsByTagName ($ nodeTag)-> item ($ index)-> nodeValue + = $ nodeValue;
Else
$ This-> seachNode-> nodeValue + = $ nodeValue;
} Else {
If ($ nodeTag)
$ This-> seachItem-> getElementsByTagName ($ nodeTag)-> item ($ index)-> nodeValue = $ nodeValue;
Else
$ This-> seachNode-> nodeValue = $ nodeValue;
}
}
Function save ($ filename ){
$ This-> writeBytes = $ this-> xml-> save ($ filename );
Return ($ this-> writeBytes )? True: false;
}
}
$ Test = new xmlDom ('student. xml ');
$ Test-> getSeachItem ('studen', 'age', '000000'); // locate the pigs with age = 103
$ Test-> update ('pig pig ', 'name', false, 1); // change the second name of pig to: pig
$ Test-> save ('new. xml'); // save it as a new file.