PHP XML DOM - 基于父属性/元素区分节点

时间:2013-05-23 18:13:31

标签: php xml dom

首先,感谢您阅读本文的时间:)

我需要帮助重新排序XML Feed。我尝试了很多东西并进行了研究,但无法提出解决方案。

<xml>
<group>
   <result>
      <title>Title</title>
      <url>URL</url>
      <text>Text</text>
   </result>
   <result>
      <title>Title</title>
      <url>URL</url>
      <text>Text</text>
   </result>
</group>
<group region=top>
   <result>
      <title>Title</title>
      <url>URL</url>
      <text>Text</text>
   </result>
</group>
<group type=bottom>
   <result>
      <title>Title</title>
      <url>URL</url>
      <text>Text</text>
      <moreinfo>
             <result>
             <title>Title</title>
             </result>
             <result>
             <title>Title</title>
             </result>
      </moreinfo>
   </result>
</group>
</xml>

我要做的是重新排序XML Feed以显示'result'中的每个节点。但是,我需要重新排序Feed,因此'group region = top'的'result'位于顶部,然后是'group'的结果,然后是'group region = bottom'的结果。

您可能会注意到另一个'结果'标记嵌套在'group region = bottom'中的'result'标记内,这导致了大多数问题。我设想解决方案的方法是使用以下伪代码:

$books = $doc->getElementsByTagName( "result" );

    foreach( $books as $book )
    {           
    if (parent_attribute = top){    

        $toptitle = $book->getElementsByTagName( "title" );
        $toptitle = $toptitle->item(0)->nodeValue;

            $topnew[]  =array("title"=>$toptitle);  
       }

            if (parent_attribute = null){

            $middletitle = $book->getElementsByTagName( "title" );
        $middletitle = $middletitle->item(0)->nodeValue;

            $middlenew[]  =array("title"=>$middletitle);            

        }

            if (parent_attribute = bottom){

            $bottomtitle = $book->getElementsByTagName( "title" );
        $bottomtitle = $bottomtitle->item(0)->nodeValue;

                if (parent_element = moreinfo){

                $moretitle = $book->getElementsByTagName( "title" );
                $moretitle = $moretitle->item(0)->nodeValue;
                }
            $bottomnew[]  =array("title"=>$bottomtitle, "more"=>$moretitle);
        } 

}

1 个答案:

答案 0 :(得分:0)

您发布的XML无效且不一致,因为属性值必须包含在""中,为了保持一致性,请参阅上面的评论。

以下是我使用simplexmlxpath执行此操作的方法,它也可以很容易地适应DOM

$xml = simplexml_load_string($x); // assuming XML in $x

$regions['top'] = $xml->xpath("group[@region='top']/result");
$regions['middle'] = $xml->xpath("group[not(@*)]/result"); // <group> with no attribute
$regions['bottom'] = $xml->xpath("group[@region='bottom']/result");

// output:
foreach ($regions as $region => $results) {

    echo "$region:<br />";
    foreach ($results as $result) {
    echo $result->title . "<br />";
    if (count($result->moreinfo) > 0)
        foreach ($result->moreinfo->result as $subresult) 
                    echo "____$subresult->title<br />";
    } // foreach $results
} // foreach $regions

看到它有效:http://codepad.viper-7.com/5adWxC