Home >Backend Development >PHP Tutorial >Custom php class (find/modify) xml document_PHP tutorial

Custom php class (find/modify) xml document_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:12:34791browse

Recently I was watching a PHP teaching video, which talked about PHP operating xml documents, and I learned a little bit about the DOMDocument class. I checked the manual myself and it was all in English, but I couldn’t understand it. But I still wrote a class myself to find xml nodes and modify node values. The background explanation is complete, let’s look at the code as follows:

Copy the code The code is as follows:

/*



Sun Wukong


White Bone Essence
140
< Introduction /name> >


*/
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('student','age','103');//Find Zhu Bajie with age=103
$test->update('Little Piggy', 'Name', false, 1); //Change Zhu Bajie's second name to: Little Piggy
$test->save('new. xml'); //Save as new file





http://www.bkjia.com/PHPjc/326709.html

www.bkjia.com

true
http: //www.bkjia.com/PHPjc/326709.html

TechArticle

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn