After reading the xml document for PHP operations, I learned some DOMDocument classes. Next I will introduce myself to writing a class to find xml nodes and modify the node values, for more information, see
After reading the xml document for PHP operations, I learned some DOMDocument classes. Next I will introduce myself to writing a class to find xml nodes and modify the node values, for more information, see
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:
The Code is as follows:
/*
<班级>
<学生 number="101">
<名字> Sun Wukong
<名字> Sun Walker
<年龄> Monkey precision
<介绍>
<学生 number="102">
<名字> Bai Gujing
<年龄> 140
<介绍> Thousands of magic
<学生 number="103">
<名字> Pig
<名字> Incompetent pig
<年龄> 200
<介绍> Sleep
*/
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.