php 操作xml文件的方法介绍。
1、xml文件
2、修改xml文件的自定义类
<?php
/**
修改xml文件
@link http://www.jb200.com
*/
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);//元素
$node = $item->getElementsByTagName($seachNode);//节点
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('学生','年龄','103');//找到 年龄=103 的猪八戒
$test->update('小猪猪', '名字', false, 1); //把猪八戒的第二个名字改成:小猪猪
$test->save('new.xml'); //保存成新文件
?>