PHP Simplexml迭代器

PHP Simplexml迭代器,php,simplexml,Php,Simplexml,如何详细说明反映以下xml结构的数组 提前谢谢 XML来源: <document> <section type="group" width="100"> <section type="list" width"50"/> <style>classe1 {color:red}</style> <section type="text" height="25">azerty<

如何详细说明反映以下xml结构的数组

提前谢谢

XML来源:

<document>
  <section type="group" width="100">
        <section type="list" width"50"/>
        <style>classe1 {color:red}</style>
        <section type="text" height="25">azerty</section>
  </section>
</document>
我尝试了以下代码,但没有成功:

<?php 
function xml2array($fName)
    {
    $sxi = new SimpleXmlIterator($fName, null, true);
    return sxiToArray($sxi);
    }

function sxiToArray($sxi)
    {
    $a = array();
    for( $sxi->rewind(); $sxi->valid(); $sxi->next() ) 
        {
        if(!array_key_exists($sxi->key(), $a))
            $a[$sxi->key()] = array();
        if($sxi->hasChildren())
            $a[$sxi->key()][] = sxiToArray($sxi->current());
        else
            {
            $a[$sxi->key() ]['attributs'] = $sxi->attributes();
            $a[$sxi->key()][] = strval($sxi->current());
            }
        }
    return $a;
    }

try
    {
    $catArray = xml2array("temp.xml");
    echo '<pre>'.print_r($catArray,true);
    }
catch(Exception $e)
    {
    echo 'ERREUR : '.$e->getMessage();
    }
?>

我已经更新了代码,以实现我认为您的目标。在一些方面,我对阵列进行了不同的管理。尤其是属性——我一次添加一个属性,以便创建键/值设置

<section type="list" width"50"/>
我还必须将XML更正为

应该是


missing=

非常感谢,这正是我想要的。好:当我在寻找帮助时,你能把它标记为已回答-帮助。
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

function xml2array($fName)
{
    $sxi = new SimpleXmlIterator($fName, null, true);
    $sxi->rewind();
    return sxiToArray($sxi)[0];
}

function sxiToArray($sxi)
{
   $a = array();
   for( $sxi->rewind(); $sxi->valid(); $sxi->next() )
    {
        $newData = [];
        $newData['key'] = $sxi->key();
        foreach ( $sxi->current()->attributes() as $key=>$attribute) {
            $newData['attributes'][(string)$key] = (string)$attribute;
        }
        if($sxi->hasChildren())  {
            $newData = array_merge( $newData, sxiToArray($sxi->current()));
        }
        else
        {
            if ( strlen(strval($sxi->current())) > 0 )    {
                $newData['content'] = strval($sxi->current());
            }
        }
        $a[] = $newData;
    }
    return $a;
}

try
{
    $catArray = xml2array("t1.xml");
    echo '<pre>'.print_r($catArray,true);
}
catch(Exception $e)
{
    echo 'ERREUR : '.$e->getMessage();
}
{
    echo 'ERREUR : '.$e->getMessage();
}
<section type="list" width"50"/>
<section type="list" width="50"/>