文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>xml2array 完美实现

xml2array 完美实现

时间:2006-08-10  来源:achun.shx

本来php手册中有simplexml2array的原型,可是我发现他有BUG,
也曾发帖提问过,没有引起大家的注意。就自己重新写了一个

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] = simplexml2array($value);
       }
       if (isset($a)) $r['@'] = $a;    // Attributes
       return $r;
   }
   return (string) $xml;
}
//这是我写的;这个有BUG请用下面的
function simplexml4array($xmle){
  $haschildren=false;
  foreach($xmle->children() as $k=>$c)
  {
    $haschildren=true;
    $r[$k]=simplexml4array($c);
  }
  foreach($xmle->attributes() as $k=>$c)
  {
    $r['@'][$k]=(string)$c;
  }
  if(!$haschildren)
  {
    $r['innerText']=(string)$xmle;
  }
  return $r;
}
//上面的有BUG,2006.08.31发现的,现在修改为
function simplexml4array($xmle){
  $haschildren=false;
  foreach($xmle->attributes() as $k=>$c)
  {
    $r[$xmle->getName()]['@att'][$k]=(string)$c;
  }
  foreach($xmle->children() as $k=>$c)
  {
    $haschildren=true;
    $res=simplexml4array($c);
    if(!empty($res)){
        $r[$xmle->getName()][]=$res;
    }
  }
  if(!$haschildren)
  {
      $str=(string)$xmle;
      if(!empty($str)){
          $r[$xmle->getName()]['@txt']=(string)$xmle;
      }
  }
  return $r;
}
//附上一个测试的例子
$str=
   
        swwss
        
            ccc
        
   
XML;
$xml = simplexml_load_string($str);
print_r(simplexml2array($xml));
print_r(simplexml4array($xml));
?>


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载