在php数组中存储xml属性

时间:2013-01-29 23:41:20

标签: php xml simplexml

我有一个这种格式的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文件,如果找到匹配项,我会进行计算。我不得不想象有一种更有效的方法可以解决这个问题。提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用XPath(请参阅:SimpleXMLElement::xpath()XPath documentation)。因此,不是你的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...

答案 1 :(得分:0)

我将XML文件预处理为关联数组(user-id / user-name =&gt; properties);

$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

}

但是,您的代码假定播放器名称是唯一的,多个播放器可能共享相同的名称(此问题已存在于您当前的代码中)