获取dom文件内容作为多维数组

时间:2016-07-19 11:22:00

标签: php multidimensional-array fonts laravel-5

我有一个名为fonts.xml的xml文件

<fonts>
   <font>
       <name>ABeeZee</name>
       <category>sans-serif</category>
    </font>
    <font>
       <name>Abel</name>
       <category>sans-serif</category>
    </font>
</fonts>

现在我想要它像一个多维数组

array = (


         0 => array(

                       name => Azeebee
                       category => sans-serif

                     ),
         1 => array(

                      name => Abel
                      category => sans-serif

                    )
 );

我试过这个

$doc = new \DOMDocument();
    $doc->load( '/fonts/font.xml' );
    $nodelist = $doc->getElementsByTagName( "font" );
    $list = array();
    foreach ($nodelist as $n)
    {
        $value = $n->nodeValue;
        $list[] = $value;
    }

    if (count($list) > 0)
    {
        echo $list[0];
    }

如何从上面的xml结构中获得这样的多维数组!有什么想法吗?

1 个答案:

答案 0 :(得分:1)

$doc = new \DOMDocument();
$doc->loadXML($str);
$nodelist = $doc->getElementsByTagName( "font" );
$list = array();
foreach ($nodelist as $n)
{
   $temp = array();
   foreach($n->childNodes as $child)
     // save all children but text node 
     if($child->nodeName != '#text') $temp[$child->nodeName] = $child->nodeValue;
   $list[] = $temp;  
}
print_r($list);

<强> demo