0

私はこのフォーマットのxmlファイルを持っています:

<?xml version="1.0" encoding="ISO-8859-1"?>
<adp_report name="Average Draft Position - Mixed 5x5" rundate="2013-01-29 17:22:10.0" begin="2013-01-26" end="2013-01-29" draftcount="126">
     <player id="500736" name="Mike Trout" position="OF" team="ANA" adp="1.66" early="1" late="4" selections="126" />
     <player id="291154" name="Ryan Braun" position="OF" team="MIL" adp="2.01" early="1" late="4" selections="126" />
     <player id="213968" name="Miguel Cabrera" position="3B" team="DET" adp="2.55" early="1" late="4" selections="126" />
</adp_report>

これをphpにロードする必要があります。ここで、name属性と、対応するadpを見つけることでアクセスできます。私はそれを使用していくつかの計算を実行し、MYSQLデータベースから呼び出されているテーブルに結果を挿入しています。これは私がこれまでに持っているものです:

$url = '...some url';
$xml = simplexml_load_file($url);    
while($row = mysqli_fetch_array($resultbat, MYSQLI_ASSOC))
  {
       echo "<td>" . $row['NAME'] . "</td>";
       ...print out some more player data from database...

       foreach($xml->player as $player)
            {
                $attr = $player->attributes();

                if($attr['name'] == $row['NAME']) //$row['NAME'] is the players name from my database
                {
                    $adp = (float) $attr['adp'];
                    $early = (int) $attr['early'];      

                    $stdev = -0.42+0.42*($adp-$early);
                    if($stdev<0)
                        $stdev = 1;
                    $chance =number_format(((1-NORMDIST($pickNumber,$adp,$stdev,TRUE))*100), 0);

                  echo "<td class='adp'>".$adp."</td>";
                  echo "<td class='chance'>".$chance."%</td>";
                  break;
                }
            }
}

foreachプレーヤーデータベースのすべての行を調べてから、を使用してxmlファイルを調べ、一致するものが見つかった場合は計算を行うため、これには処理に時間がかかります。これを実行するためのより効率的な方法があることを想像する必要があります。前もって感謝します。

4

2 に答える 2

1

XPathを使用できます(SimpleXMLElement :: xpath()およびXPathのドキュメントを参照)。したがって、foreachループの代わりに、これは次のとおりです。

$player = $xml->xpath('//player[@name="' . $row['NAME'] . '"]');
if (is_array($player) && count($player)) {
    $player = $player[0];
} else {
    continue; // not found
}
$attr = $player->attributes();
// and so on...
于 2013-01-30T00:00:02.070 に答える
0

XMLファイルを連想配列(user-id / user-name =>プロパティ)に前処理します。

$url = '...some url';
$xml = simplexml_load_file($url);

$players = array();

foreach($xml->player as $player) {
    $attr = $player->attributes();

    // cast the SimpleXMLElement to a string
    $username = (string) $attr['name'];
    $players[$username] = $attr;
}

次に、データベースからデータを取得し、XMLからの結果を照合します

while($row = mysqli_fetch_array($resultbat, MYSQLI_ASSOC)) {
     if(!array_key_exists($row['NAME'], $players)) {
          // player was not found in the XML
          continue;
     }

     // get the player's properties by matching the 'name'
     $player_stats = $players[$row['NAME']];

     // here, process player_stats

}

ただし、コードはプレーヤー名が一意であると想定しているため、複数のプレーヤーが同じ名前を共有している可能性があります(この問題は現在のコードにすでに存在していました)

于 2013-01-29T23:49:50.037 に答える