<?php /** * xml操作基类 */ class XmlBase { public function __construct() { } /** * 加载xml * @param string $xml xml路径或xml字符串 * @param bool $isXmlStr 是否是xml字符串 */ protected function _loadXml($xml, $isXmlStr = FALSE) { $xmlObj = new DOMDocument(); if ($isXmlStr) { $xmlObj->loadXML($xmlNewStr); } else { $xmlObj->load($xml); } return $xmlObj; } /** * 获取某个标签节点 * @param $parentnode 父节点 * @param $tagName 标签名 // 不区分大小写 * @return node 节点对象 */ protected function _getNode($parentNode, $tagName) { $childNodes = $this->_getNodes($parentNode); foreach ($childNodes as $node) { $nodeName = strtolower(trim($node->nodeName)); $tagName = strtolower(trim($tagName)); if ($nodeName == $tagName) { return $node; } } return NULL; } /** * 获取xml子节点 * @param $parentNode 父节点 * @param $tagName 子节点标签 // 不区分大小写 */ protected function _getNodes($parentNode, $tagName = '') { $nodes = array(); if ($tagName) { $nodes = $this->_getSpecialNodes($parentNode, $tagName); } else { $nodes = $this->_getAllNodes($parentNode); } return $nodes; } /** * 获取所有的节点 * @param $parentNode 父节点 */ protected function _getAllNodes($parentNode) { $nodes = array(); foreach ($parentNode->childNodes as $node) { if ($node->nodeType == 1) { $nodes[] = $node; } } return $nodes; } /** * 获取指定标签的节点 * @param $parentNode 父节点 * @param $tagName 节点名称 */ protected function _getSpecialNodes($parentNode, $tagName) { $nodes = array(); $tagName = strtolower(trim($tagName)); foreach ($parentNode->childNodes as $node) { $nodeName = strtolower(trim($node->nodeName)); if ($node->nodeType == 1 && $nodeName == $tagName) { $nodes[] = $node; } } return $nodes; } /** * 获取节点属性值 * * @param $node 节点对象 * @param $attrName 节点名字 // 不区分大小写 */ protected function _getAttr($node, $attrName) { $attrName = strtolower($attrName); foreach ($node->attributes as $attr) { $nodeName = strtolower($attr->nodeName); //$nodeValue = strtolower($attr->nodeValue); $nodeType = strtolower($attr->nodeType); if ($nodeType == 2 && $nodeName == $attrName) { unset($attrName, $nodeName, $nodeType); return $attr->nodeValue; } } return ''; } } ?>
PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用: