<?php
/*
Sample: $results = XMLParser::load('<xml ....');
$results = XMLParser::load(VSCHEMAS.'/Users.edit.xml');
*/
/**
* Abstract XMLParser class. A non-instantiable class that uses SimpleXML to parse XML, based on a path or body passed into the load method
*
* @abstract
*/
abstract class XMLParser {
/**
* convert function. Converts a SimpleXMLElement object to an associative array, usable for iteration
*
* @see http://www.if-not-true-then-false.com/2009/12/php-tip-convert-stdclass-object-to-multidimensional-array-and-convert-multidimensional-array-to-stdclass-object/
* @access private
* @static
* @param mixed $node node to convert to a non-object based value
* @return array associative array of the passed in node/object, ultimately representing the initially passed in object as an associative array
*/
private static function convert($node) {
if(is_object($node))
$node = get_object_vars($node);
if(is_array($node))
return array_map(array('self', 'convert'), $node);
return $node;
}
/**
* load function. Loads a source (either a local path or source body) document, and returns as associative array of it's results
*
* @access public
* @static
* @param string $source xml body, or path to local xml file
* @return array SimpleXML results, parsed as an associative array
*/
public static function load($source) {
$path = false;
if(preg_match('/^\//', $source) > 0)
$path = true;
$simpleXMLElement = new SimpleXMLElement($source, LIBXML_NOENT, $path);
return self::convert($simpleXMLElement);
}
}
?>
我正在使用上面的代碼來解析xml文件並將它們轉換爲更可遍歷的數組。儘管我遇到了一個問題。當我有一些樣本XML,如:XML解析:標籤應該是數值數組?
<fields>
<rule whatever="lolcats" />
</fields>
與
<fields>
<rule whatever="lolcats" />
<rule whatever="lolcats" />
</fields>
結果數組是不相符的。也就是說,在第一種情況下,它的格式爲:
Array
(
[field] => Array
(
[@attributes]...
而在後者,它的格式爲:
Array
(
[field] => Array
(
[0]...
我想說這裏,是它的索引子xml元素的數值,這是我想要的,但只有當超過1.什麼想要改變什麼總是讓它們在數值上進行索引,而不是直接引用單一元素的@attributes數組?
任何幫助將非常感激:d
我試過了。轉換功能真的很麻煩。任何其他的想法? – onassar 2010-01-19 01:51:21