Home > Backend Development > PHP Tutorial > 自定义php类(查找/修改)xml文档_PHP

自定义php类(查找/修改)xml文档_PHP

WBOY
Release: 2016-06-01 12:07:52
Original
950 people have browsed it

近期在看PHP的教学视频,其中讲到了 PHP 操作 xml 文档,学了点儿 DOMDocument 类。自己查手册又全英文,看不大懂。但还是自己写了个类,实现了查找 xml 节点,并修改节点值。背景解说完毕,且看代码如下:
复制代码 代码如下:
/*



孙悟空名字>
孙行者名字>
猴精猴精年龄>
介绍>
学生>

白骨精名字>
140年龄>
幻化万千介绍>
学生>

猪八戒名字>
猪无能名字>
200年龄>
能吃会睡介绍>
学生>
班级>
*/
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; $iitems->length; $i++){
$item = $this->items->item($i);//元素
$node = $item->getElementsByTagName($seachNode);//节点
for($j = 0; $jlength; $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('学生','年龄','103');//找到 年龄=103 的猪八戒
$test->update('小猪猪', '名字', false, 1); //把猪八戒的第二个名字改成:小猪猪
$test->save('new.xml'); //保存成新文件

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template