PHP封装的XML简单操作类完整实例

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP封装的XML简单操作类完整实例脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

本文实例讲述了PHP封装的XML简单操作类。分享给大家供大家参考,具体如下:

xML_dom.PHP封装类文件

PHP;">
dbfile = $db_file;
    if(!file_exists($db_file))
    {
//     die('未找到数据库文件');
      $this->dblink = new DOMDocument('1.0','utf-8');
      $root = $this->dblink->createElement('root');
      $this->dblink->apPEndChild($root);
      $this->dblink->formatOutput = true;  // xml文件保留缩进样式
      $this->dblink->save($this->dbfile);
    }
    else
    {
      $this->dblink = new DOMDocument();
      $this->dblink->formatOutput = true;
      $this->dblink->load($this->dbfile);
    }
  }
  /**
   * 遍历所有元素
   * ===============================================
   * 标准xml文件一个元素可能有n个属性,可用自定义键[nodevalue]获取元素值
   * 
   * 
* 标题一 * 内容一 * 文件,没有属性键值一一对应 * * * * 1 * <a href="https://www.js-code.com/tag/biaoti/" target="_blank" class="keywords">标题</a>一 * 详细内容 * * * @param $node * @return array */ function getData($node=0){ if(!$node) { $node = $this->dblink->documentElement; } $array = array(); foreach($node->attributes as $attribute) { $key = $attribute->nodeName; $val = $attribute->nodeValue; $array[$key] = $val; } if(count($array)) // 有属性,则用[nodevalue]键代表值 { $array['nodevalue'] = $node->nodeValue; } // 递归遍历所有子元素 $node_child = $node->FirstChild; while($node_child) { if(XML_ELEMENT_NODE == $node_child->nodeType) { $tagname = $node_child->tagName; $result = $this->getData($node_child); if(isset($array[$tagname])) // 发现有重复tagName的子元素存在,所以改用数组存储重复tagName的所有子元素 { if(!is_array($array[$tagname][0])) { $tmp = $array[$tagname]; $array[$tagname] = array(); $array[$tagname][] = $tmp; } $array[$tagname][] = $result; } else { $array[$tagname] = $result; } } $node_child = $node_child->nextSibling; } if(!count($array)) // 没有子元素&没有属性=最末子元素,就返回该元素的nodeValue值 { return $node->nodeValue; } return $array; } /** * 把array数据写到xml文件(覆盖) * @param $data */ public function setData($data,&$node=0) { $is_root = false; if(!$node) { $is_root = true; $node = $this->dblink->documentElement; // 清除原数据 $remove = array(); $node_child = $node->firstChild; while($node_child) { $remove[] = $node_child; $node_child = $node_child->nextSibling; } foreach($remove as $r) { $node->removeChild($r); } } if(is_array($data)) { foreach($data as $k=>$v) { if(is_array($v)) { foreach($v as $r) { $ITem = $this->dblink->createElement($k); $result = $this->setData($r,$item); $node->appendChild($result); } } else { $item = $this->dblink->createElement($k); $value = $this->dblink->createTextNode($v); $item->appendChild($value); $node->appendChild($item); } } } else { $item = $this->dblink->createTextNode($data); $node->appendChild($item); } if($is_root) { $this->dblink->save($this->dbfile); // 覆盖写入 } else { return $node; } } }

脚本宝典总结

以上是脚本宝典为你收集整理的PHP封装的XML简单操作类完整实例全部内容,希望文章能够帮你解决PHP封装的XML简单操作类完整实例所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。