核心代码是网上baidu出来的,自己封装了一下。测试的时候PHP4非常正常,PHP5就不好使了。思索好长时间,原来PHP5里对array_merge函数进行了改造,限制了参数必须是array型的。稍加改造,OK了。可以完美的把XML转为数组。帖出来,大家共享。 好图
<?
class ParserXml
{
function ParserXml()
{
}
function ParserXmlByUrl($url)
{
$fp = @fopen($url,'r');
if (!$fp){
return 1;
}
$xmlstr = fread($fp,1024);
@fclose($fp);
if ($xmlstr === false){
return 0;
}
return $this->GetXMLTree($xmlstr);
}
function GetXMLTree($xmldata)
{
ini_set ('track_errors', '1');
$xmlreaderror = false;
$parser = xml_parser_create();
xml_parser_set_option ($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option ($parser, XML_OPTION_CASE_FOLDING, 0);
if (!xml_parse_into_struct ($parser, $xmldata, $vals, $index)) {
$xmlreaderror = true;
return 0;
}
xml_parser_free($parser);
if(!$xmlreaderror){
$result = array ();
$i = 0;
if (isset($vals[$i]['attributes'])){
foreach (array_keys ($vals [$i]['attributes']) as $attkey)
$attributes[$attkey] = $vals[$i]['attributes'][$attkey];
}
$result[$vals [$i]['tag']] = array_merge((array)$attributes, $this->GetChildren($vals, $i, 'open'));
}
ini_set('track_errors', '0');
return $result;
}
function GetChildren ($vals, &$i, $type)
{
if ($type == 'complete') {
if (isset ($vals [$i]['value']))
return ($vals [$i]['value']);
else
return '';
}
$children = array ();
while ($vals [++$i]['type'] != 'close') {
$type = $vals [$i]['type'];
if (isset ($children [$vals [$i]['tag']])) {
if (is_array ($children [$vals [$i]['tag']])) {
$temp = array_keys ($children [$vals [$i]['tag']]);
if (is_string ($temp [0])) {
$a = $children [$vals [$i]['tag']];
unset ($children [$vals [$i]['tag']]);
$children [$vals [$i]['tag']][0] = $a;
}
} else {
$a = $children [$vals [$i]['tag']];
unset ($children [$vals [$i]['tag']]);
$children [$vals [$i]['tag']][0] = $a;
}
$children [$vals [$i]['tag']][] = $this->GetChildren ($vals, $i, $type);
} else
$children [$vals [$i]['tag']] = $this->GetChildren ($vals, $i, $type);
if (isset ($vals [$i]['attributes'])) {
$attributes = array ();
foreach (array_keys ($vals [$i]['attributes']) as $attkey)
$attributes [$attkey] = $vals [$i]['attributes'][$attkey];
if (isset ($children [$vals [$i]['tag']])) {
if ($children [$vals [$i]['tag']] == '') {
unset ($children [$vals [$i]['tag']]);
$children [$vals [$i]['tag']] = $attributes;
}
elseif (is_array ($children [$vals [$i]['tag']])) {
$index = count ($children [$vals [$i]['tag']]) - 1;
if ($children [$vals [$i]['tag']][$index] == '') {
unset ($children [$vals [$i]['tag']][$index]);
$children [$vals [$i]['tag']][$index] = $attributes;
}
$children [$vals [$i]['tag']][$index] = array_merge ($children [$vals [$i]['tag']][$index], $attributes);
} else {
$value = $children [$vals [$i]['tag']];
unset ($children [$vals [$i]['tag']]);
$children [$vals [$i]['tag']]['value'] = $value;
$children [$vals [$i]['tag']] = array_merge ($children [$vals [$i]['tag']], $attributes);
}
} else
$children [$vals [$i]['tag']] = $attributes;
}
}
return $children;
}
}
?>
发现"插入代码"不好使:)