使用PHP,我想编写一个列出所有元素+子元素及其所有属性的函数。我想使用DOM,但不是SimpleXMLElement。
XML SAMPLE
<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
答案 0 :(得分: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']);