2011-10-23 58 views
0

我想用php簡單的xml解析一些這樣的樹。php簡單的xml孩子點數加

如何加上所有的tree->item->object->num

我想獲得一個int 162 + 4 + 7 + 2 + 1

<tree> 
    <item> 
    <object> 
     <num>2</num> 
    </object> 
    <object> 
     <num>4</num> 
    </object> 
    </item> 
    <item> 
    <object> 
     <num>7</num> 
    </object> 
    <object> 
     <num>2</num> 
    </object> 
    </item> 
    <item> 
    <object> 
     <num>1</num> 
    </object> 
    </item> 
</tree> 

回答

2

簡單/醜陋的版本:

$dom = new DOMDocument(); 
$dom->loadXML($your_xml); 

$xp = new DOMXPath($dom); 

$nums = $xp->query('//num'); 
$sum = 0; 
foreach($nums as $num) { 
    $sum += $num->nodeValue; 
} 
echo $sum; 
4
$xml = new SimpleXMLElement($yourXMLString); 

$acc = 0; 
foreach($xml->item as $item) 
{ 
    foreach($item->object as $object) 
    { 
     $acc += $object->num; 
    } 
} 

echo $acc; // 16 
0
$tree = simplexml_load_string($xmlstring); 
$nums = $tree->xpath('/tree/item/object/num'); 

// Array functions to sum the numbers 
$sum = array_sum(array_map('intval', $nums)); 

// or, Loop to sum the number 
$sum = 0; 
foreach ($nums as $num) { 
    $sum += $num; 
}