1

わかりましたので、この例のようなxmlがあるとしましょう。

   <?xml version="1.0" encoding="UTF-8"?>

   <stats id="865" name="blaah">
       <example name="blaahblaah">
           <example1>
               <x ppoints="500"/>
           </example1>
           <example2>
               <x ppoints ="150"/>
               <x points ="500"/>
               <x ppoints ="140"/>
               <x points="200"/>
           </example2>
       </example>
   </stats>

私がここでやろうとしているのは、すべてのポイントを取得して 1 つの数値に丸め、すべてのポイントを 1 つの数値に丸めることです。

統計: 「ポイントの切り上げ」pp & 「ポイントの切り上げ」p

誰か助けて?どうもありがとう

4

1 に答える 1

2

ppointsこの場合、ドキュメントの構造に複数の「サンプル」ノードが含まれる可能性があることを理解しているため、XML ドキュメントをロードし、XPath 式を使用して属性と属性を持つすべてのノードを取得するのが最善の方法だと思いpointsます。

XPath を使用すると、2 つの解決策が考えられます。SimpleXMLElement::xpathを使用して、必要なすべてのノードを取得し、それらを手動で合計します。もう 1 つは、DOMXPath::evaluateを使用して、任意のタイプの XPath 式を評価し、XPath を使用して値を合計することを可能にします。後者のソリューションはより簡単です。

DOMXPath::評価する

<?php

$doc = new DOMDocument;
$doc->load('file.xml');
$xpath = new DOMXPath($doc);

$sum_ppoints = $xpath->evaluate('sum(//x/@ppoints)');
$sum_points = $xpath->evaluate('sum(//x/@points)');

print "Ppoints: $sum_ppoints; Points: $sum_points\n";

?>

SimpleXMLElement::xpath

<?php

// Load XML file
$file = "file.xml";
$content = file_get_contents($file);
$xml = new SimpleXMLElement($content);

// Compute sum ppoints
$sum_ppoints = 0;
$nodes = $xml->xpath('//x[@ppoints]');
foreach ($nodes as $node) {
    $sum_ppoints += $node->attributes()->ppoints;
}

// Compute sum points
$sum_points = 0;
$nodes = $xml->xpath('//x[@points]');
foreach ($nodes as $node) {
    $sum_points += $node->attributes()->points;
}

print "Ppoints: $sum_ppoints; Points: $sum_points\n";

?>
于 2012-12-11T23:50:52.637 に答える