日期:2014-05-17  浏览次数:20485 次

PHP解析XML转成数组 在线等
XML code

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <a>
      <b name='name' value='value' />
      <b name='name' value='value' />
      <b name='name' value='value' />
   </a>
   <a>
      <b name='name' value='value' />
      <b name='name' value='value' />
      
   </a>
   <a>
      <b name='name' value='value' />
      <b name='name' value='value' />
      <b name='name' value='value' />
     <b name='name' value='value' />
   </a>
</root>


  解析成数组:
PHP code

    Array(
       [0]=>Array(
            [0]=>Array(name=>'name',value=>'value'),
            [1]=>Array(name=>'name',value=>'value'),
            [2]=>Array(name=>'name',value=>'value')
       ),
       [1]=>Array(
         [0]=>Array(name=>'name',value=>'value'),
         [1]=>Array(name=>'name',value=>'value'),
         [2]=>Array(name=>'name',value=>'value')
       ),
       [2]=>Array(
         [0]=>Array(name=>'name',value=>'value'),
         [1]=>Array(name=>'name',value=>'value'),
         [2]=>Array(name=>'name',value=>'value')
      ),
)



------解决方案--------------------
PHP code
<?php
$xml=<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <a>
      <b name='name' value='value' />
      <b name='name' value='value' />
      <b name='name' value='value' />
   </a>
   <a>
      <b name='name' value='value' />
      <b name='name' value='value' />
      
   </a>
   <a>
      <b name='name' value='value' />
      <b name='name' value='value' />
      <b name='name' value='value' />
     <b name='name' value='value' />
   </a>
</root>
XML;

$obj=simplexml_load_string($xml);
foreach($obj as $k=>$v){
    $temp=array();
    foreach ($v->b as $sv) {
        $a=(array)$sv->attributes();
        $temp[]=$a['@attributes'];
    }
    $arr[]=$temp;
}
print_r($arr);

------解决方案--------------------
PHP code
$s =<<< XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <a>
      <b name='name' value='value' />
      <b name='name' value='value' />
      <b name='name' value='value' />
   </a>
   <a>
      <b name='name' value='value' />
      <b name='name' value='value' />
   </a>
   <a>
      <b name='name' value='value' />
      <b name='name' value='value' />
      <b name='name' value='value' />
     <b name='name' value='value' />
   </a>
</root>
XML;

$xml = simplexml_load_string($s);

foreach($xml as $item1) {
  $r = array();
  foreach($item1 as $item2) {
    $t = array();
    foreach($item2->attributes() as $k=>$v) {
      $t[] = array($k => "$v");
    }
    $r[] = $t;
  }
  $res[] = $r;
}

print_r($res);