-2

使用 PHP,我想编写一个列出所有元素 + 子元素及其所有属性的函数。我想使用 DOM,但不是 SimpleXMLElement。

XML 样本

 <DOM>
   <TAB id="ID1" width="30,1" height="0,5" >
     <CHILD aaa="50.12" bbb="50.45" />
     <CHILD aaa="78.06" bbb="6.12" />
   </TAB> 
   <TAB id="ID2" width="15,7" height="1,8" >
     <CHILD aaa="2.60" bbb="5.32" />
   </TAB> 
 </DOM>

我需要这样的输出:

TAB id:ID1  width:30.1  height:0.5
  CHILD aaa:50.12 bbb:50.45
  CHILD aaa:78.06 bbb:6.12
TAB id:ID2  width:15.7  height:1.8
  CHILD aaa:2.60 bbb:5.32
4

1 回答 1

2

尽管您特别要求不要使用 SimpleXML 来引用另一个问题,但我对使用以下内容的计算没有任何问题:

<?php

$xml = new SimpleXMLElement('<DOM>
   <TAB id="ID1" width="30,1" height="0,5" >
     <CHILD aaa="50.12" bbb="50.45" />
     <CHILD aaa="78.06" bbb="6.12" />
   </TAB> 
   <TAB id="ID2" width="15,7" height="1,8" >
     <CHILD aaa="2.60" bbb="5.32" />
   </TAB> 
 </DOM>');


foreach($xml->TAB as $tab)
{
    $attrib = $tab->attributes();
    echo "TAB id:".$attrib['id']."  width:".str_replace(",",".", $attrib['width'])."  height:".str_replace(",",".", $attrib['height'])."\n";

    foreach($tab->CHILD as $child)
    {
        $attrib = $child->attributes();
        echo "  CHILD aaa:".$attrib['aaa']."  bbb:".str_replace(",",".", $attrib['bbb'])."\n";
    }       
}

使用以下测试,计算按预期工作:

echo (float) str_replace(",",".", $attrib['width']) * (float) str_replace(",",".", $attrib['height']);
于 2013-08-03T18:58:17.823 回答