推荐初学XML者两个PHP解析XML的函数

很简单的XML读取函数。以前没有研究过XML配置文件,今天突然要用到。翻了手册拿到两个函数,很好用的函数。先把文件读取出来,用file_get_contetns,然后用函数处理。看看你的数组吧。。。一切搞定!!! 推荐使用第二个 function XMLToArray($xml) { if ($xml instanceof SimpleXMLElement) { $children = $xml->children(); $return = null; } foreach ($children as $element => $value) { if ($value instanceof SimpleXMLElement) { $values = (array)$value->children(); if (count($values) > 0) { $return[$element] = XMLToArray($value); } else { if (!isset($return[$element])) { $return[$element] = (string)$value; } else { if (!is_array($return[$element])) { $return[$element] = array($return[$element], (string)$value); } else { $return[$element][] = (string)$value; } } } } } if (is_array($return)) { return $return; } else { return $false; } } function simplexml2ISOarray($xml) { if (get_class($xml) == ‘SimpleXMLElement’) { $attributes = $xml->attributes(); foreach($attributes as $k=>$v) { if ($v) $a[$k] = (string) $v; } $x = $xml; $xml = get_object_vars($xml); } if (is_array($xml)) { if (count($xml) == 0) return (string) $x; // for CDATA foreach($xml as $key=>$value) { $r[$key] = simplexml2ISOarray($value); // original line instead of the following if statement: //$r[$key] = simplexml2ISOarray($value); if ( !is_array( $r[$key] ) ) $r[$key] = $r[$key]; } if (isset($a)) $r[‘@’] = $a; // Attributes return $r; } return (string) $xml; }

Comments