• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

php 搞代码 3年前 (2022-01-26) 21次浏览 已收录 0个评论

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

 <BR>/* <BR><?xml version="1.0" encoding="UTF-8"?> <BR> <BR> <BR>孙悟空 <BR>孙行者 <BR>猴精猴精 <BR> <BR> <BR> <BR>白骨精 <BR>140 <BR>幻化万千 <BR> <BR> <BR>猪八戒 <BR>猪无能 <BR>200 <BR>能吃会睡 <BR> <BR> <BR>*/ <BR>class xmlDom{ <BR>public $version; <BR>public $encoding; <BR>private $xm<strong style="color:transparent">本文来源gao@daima#com搞(%代@#码@网&</strong><strong>搞gaodaima代码</strong>l; <BR>private $items; <BR>private $seachNode = ''; <BR>private $seachItem = ''; <BR>private $seachValue = ''; <BR>public $writeBytes = 0; <BR>function __construct($xmlFile ='', $version ='1.0', $encoding = 'UTF-8'){ <BR>$this->version = $version; <BR>$this->encoding = $encoding; <BR>$this->xml = new DOMDocument($version, $encoding); <BR>if($xmlFile)$this->xml->load($xmlFile); <BR>} <BR>function getRootEle($rootTag){ <BR>$this->xmlRoot = $this->xml->getElementsByTagName($rootTag)->item(0); <BR>} <BR>function getSeachItem($itemsTag, $seachNode, $seachValue){ <BR>$this->items = $this->xml->getElementsByTagName($itemsTag); <BR>$this->items->length; <BR>for($i=0; $iitems->length; $i++){ <BR>$item = $this->items->item($i);//元素 <BR>$node = $item->getElementsByTagName($seachNode);//节点 <BR>for($j = 0; $jlength; $j++){ <BR>$subNode = $node->item($j); <BR>if($seachValue == $subNode->nodeValue){ <BR>$this->seachNode = $subNode; <BR>$this->seachItem = $item; <BR>$this->seachValue = $subNode->nodeValue; <BR>break(2); <BR>} <BR>} <BR>} <BR>return ($this->seachNode) ? true : false; <BR>} <BR>function update($nodeValue, $nodeTag = '',$append = false, $index = 0){ <BR>if($append){ <BR>if($nodeTag) <BR>$this->seachItem->getElementsByTagName($nodeTag)->item($index)->nodeValue += $nodeValue; <BR>else <BR>$this->seachNode->nodeValue += $nodeValue; <BR>}else{ <BR>if($nodeTag) <BR>$this->seachItem->getElementsByTagName($nodeTag)->item($index)->nodeValue = $nodeValue; <BR>else <BR>$this->seachNode->nodeValue = $nodeValue; <BR>} <BR>} <BR>function save($filename){ <BR>$this->writeBytes = $this->xml->save($filename); <BR>return ($this->writeBytes) ? true : false; <BR>} <BR>} <BR>$test = new xmlDom('student.xml'); <BR>$test->getSeachItem('学生','年龄','103');//找到 年龄=103 的猪八戒 <BR>$test->update('小猪猪', '名字', false, 1); //把猪八戒的第二个名字改成:小猪猪 <BR>$test->save('new.xml'); //保存成新文件 <BR>

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:自定义php类(查找/修改)xml文档_php技巧
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址