XML:如何通过php从多路径读取

时间:2015-11-30 09:32:02

标签: php xml xpath foreach

我有一个XML文件,如:

<competition competition_id="9">
<season season_id="11643">
<round round_id="31545" name="Regular Season">
<match match_id="2054191" team_A_name="Bayern München" team_B_name="Hamburger SV" />
<match match_id="2054193" team_A_name="Bayer Leverkusen" team_B_name="Hoffenheim" />
</round>
</season>
</competition>

不,我尝试将此文件保存到我的数据库中,如:

$xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA); 
$competitions = $xml->xpath('//competition');
$seasons = $xml->xpath('//season');
$rounds = $xml->xpath('//round');
$matchs = $xml->xpath('//match');

foreach ($competitions as $competition) {

  foreach ($seasons as $season) {

    foreach ($rounds as $round) {

      foreach ($matchs as $match) {

        $competition_id = $competition->attributes()->competition_id;
        $season_id = $competition->season->attributes()->season_id;
        $round_id = $competition->season->round->attributes()->round_id;
        $match_id = $competition->season->round->match->attributes()->match_id;

        $matches_insert = mysql_query("INSERT INTO `matches` (`competition_id` ,`season_id` ,`round_id` ,`match_id` ,`team_A_name`,`team_B_name`) VALUES ('$competition_id',  '$season_id',  '$round_id',  '$match_id', '$team_A_name',   '$team_B_name');");
      }
    }
  }
}

此代码仅保存第一条记录,并将其复制两次。

如何保存此拖曳记录而不重复?

1 个答案:

答案 0 :(得分:0)

您可以像这样迭代DOM:

$xml = simplexml_load_url($url,"SimpleXMLElement",LIBXML_NOCDATA);
$competitions = $xml->xpath('//competition');
foreach ($competitions as $competition) {
    $competition_id = $competition->attributes()->competition_id;

    foreach ($competition->season as $season) {
        $season_id = $season->attributes()->season_id;

        foreach ($season->round as $round) {
            $round_id = $round->attributes()->round_id;

            foreach ($round->match as $match) {
                $match_id = $match->attributes()->match_id;
                // Query here
            }
        }
    }
}

在您的示例中使用mysqli_query()时,不推荐使用MySQL扩展,但请考虑使用预准备语句。