怎么自定义php类查找或修改xml文档

发布时间:2021-07-22 18:25:02 作者:chen
来源:亿速云 阅读:110

这篇文章主要讲解了“怎么自定义php类查找或修改xml文档”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么自定义php类查找或修改xml文档”吧!

近期在看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类查找或修改xml文档”的内容了,经过本文的学习后,相信大家对怎么自定义php类查找或修改xml文档这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. 通用自定义XML配置类
  2. Dom4j修改xml文档引入的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:在.NET如何使用JSON作为数据交换格式

下一篇:aix was日志乱码如何解决

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》