php&在xml中求和属性值

时间:2012-04-16 23:58:23

标签: php xml xml-parsing

我有一个xml文件,我正在用php阅读。目前我已经加载了xml,其内容很好地显示在表中。 目前我正在尝试总结“点”属性的所有值,计算其平均值并显示该数字。

任何帮助都是最受欢迎的,因为目前我不得不在计算器上添加所有这些数字。

xml的基本结构,大大简化了:

<data>

...

<season id="1" foo1="bar1" points="1" />  
<season id="2" foo2="bar2" points="2" />
<season id="3" foo3="bar3" points="4" />
<season id="4" foo4="bar4" points="0" /> 

...

</data>

我的php:

<?php
$url = "data.xml";
$xml = simplexml_load_file($url);

// loop through xml
foreach($xml->season as $season)
{

...

echo "<tr>";
echo "<td>".$season["id"]."</td>";
echo "</tr>";

...

}
// end ofloop

... 

// don't really know what to do here
// to get to the paragaph below:


<p>Average points = $average_points </p>
?>

2 个答案:

答案 0 :(得分:3)

$total = 0;
$items = 0;

foreach ($xml->season as $season) {

    ...

    $total += $season['points'];
    $items++;

}

if ($items) {
    $average_points = $total / $items;
}

答案 1 :(得分:2)

你走了。

<?php
     $url = "data.xml";
     $xml = simplexml_load_file($url);

     foreach($xml->season as $season)
     {
          echo "<tr>";
          echo "<td>".$season->id."</td>";
          echo "</tr>";
     }

     $count = 0;
     $sum = 0

     foreach($xml->season as $season)
     {
          ++$count;
          $sum += $season->points;
     }

     $average = $sum / $count;