代码之家  ›  专栏  ›  技术社区  ›  FlyingCat

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

  •  0
  • FlyingCat  · 技术社区  · 12 年前

    我在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 回复  |  直到 12 年前
        1
  •  2
  •   jchapa    12 年前

    两件事:

    1. 你需要匹配你的 <ob> </objective> 标签。

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

    例子:

    $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());
            }
        }
    }
    
        2
  •  1
  •   alwaysLearn    12 年前

    你需要重新打电话

    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);
         }   
     }
    }