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

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

/*
<?xml version="1.0" encoding="UTF-8"?>
<班级>
<学生 number="101">
<名字>孙悟空</名字>
<名字>孙行者</名字>
<年龄>猴精猴精</年龄>
<介绍></介绍>
</学生>
<学生 number="102">
<名字>白骨精</名字>
<年龄>140</年龄>
<介绍>幻化万千</介绍>
</学生>
<学生 number="103">
<名字>猪八戒</名字>
<名字>猪无能</名字>
<年龄>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; $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'); //保存成新文件

相关文章

PHP文字转图片功能原理与实现方法分析

PHP文字转图片功能原理与实现方法分析

本文实例讲述了PHP文字转图片功能。分享给大家供大家参考,具体如下: 这项功能主要用于对邮箱地址、手机等可能被网络爬虫抓取的重要信息的处理。将文字转化为图片绝对是个好注意。验证码的基本生...

使用PHP生成PDF方法详解

利用PHP编码生成PDF文件是一个非常耗时的工作。在早期,开发者使用PHP并借助FPDF来生成PDF文件。但是如今,已经有很多函数库可以使用了,并且能够从你提供的HTML文件生成PDF文...

PHP 数组遍历方法大全(foreach,list,each)

在PHP中数组分为两类: 数字索引数组和关联数组。 其中数字索引数组和C语言中的数组一样,下标是为0,1,2… 而关联数组下标可能是任意类型,与其它语言中的hash,map等结构相似。...

PHP的serialize序列化数据以及JSON格式化数据分析

PHP的serialize是将变量序列化,返回一个具有变量类型和结构的字符串表达式,而JSON则是一种更轻、更友好的用于接口(AJAX、REST等)数据交换的格式。 其实两者都是以一种字...

PHP 循环列出目录内容的函数代码

复制代码 代码如下: function list_files($dir) { if(is_dir($dir)) { if($handle = opendir($dir)) { while...