如何检索xml中所有元素内的所有数据?

时间:2013-03-21 17:19:53

标签: php xml simplexml

我在php中获取xml数据时出现问题

我的xml相当复杂,标签中有几个嵌套的子项。

XML

?xml version="1.0" encoding="UTF-8"?>

<book id="5">
<title id="76">test title</title>
<figure id="77"></figure>

<ch id="id78">
<aa id="80"><emph>content1</emph></aa>
<ob id="id_84" page-num="697" extra-info="4"><emph type="bold">opportunity.</emph></ob>
<ob id="id_85" page-num="697" extra-info="5"><emph type="bold">test data.</emph></ob>
<para id="id_86" page-num="697">2008.</para>

<body>
   ..more elements
   <content>more contents..
   </content>
</body>
</ch>

我的代码

//I need to load many different xml files.

 $xml_file = simplexml_load_file($filename);
          foreach ($xml_file->children() as $child){
              echo $child->getName().':'. $child."<br>";
          }

上面的代码只会显示

book, title, figure, ch但不是ch标记内的元素。如何显示每个标签内的所有元素?有小费吗?非常感谢!

2 个答案:

答案 0 :(得分:2)

两件事:

  1. 您需要与<ob> </objective>代码匹配。

  2. 你的foreach需要递归。您应该检查foreach中的每个项目是否都有一个孩子,然后递归地预测这些元素。我建议您使用单独的函数来递归调用。

  3. 示例:

    $xml_file = simplexml_load_file($filename);
    parseXML($xml_file->children());
    function parseXML($xml_children)
    {
        foreach ($xml_children as $child){
            echo $child->getName().':'. $child."<br>";
            if ($child->count() > 0)
            {
                parseXML($child->children());
            }
        }
    }
    

答案 1 :(得分:1)

您需要进行递归调用

parseAllXml($xml_file);

function parseAllXml($xmlcontent)
{
 foreach($xmlcontent->children() as $child)
   {
     echo $child->getName().':'. $child."<br>";
     $is_further_child = ( count($child->children()) >0 )?true:false;  
     if( $is_further_child )
     {
        parseAllXml($child);
     }   
 }
}
相关问题