0

我正在尝试将 xpath 与 DOMDocument 结合使用来尝试解析我的 xml 并插入到表中。

除了 $halftimescore 之外,我所有的变量都正确插入 - 这是为什么呢?

这是我的代码:

<?php

  define('INCLUDE_CHECK',true);
  require 'db.class.php';

  $dom = new DOMDocument();
  $dom ->load('main.xml');

  $xpath = new DOMXPath($dom);
  $queryResult = $xpath->query('//live/Match/Results/Result[@name="HT"]');
  foreach($queryResult as $resulty) {
    $halftimescore=$resulty->getAttribute("value");
  }      


  $Match = $dom->getElementsByTagName("Match"); 
  foreach ($Match as $match) {

    $matchid = $match->getAttribute("id");
    $home = $match->getElementsByTagName("Home");
    $hometeam = $home->item(0)->getAttribute("name");
    $homeid = $home->item(0)->getAttribute("id");
    $away = $match->getElementsByTagName("Away");
    $awayid = $away->item(0)->getAttribute("id");
    $awayteam = $away->item(0)->getAttribute("name");

    $leaguename = $match->getElementsByTagName("league");
    $league = $leaguename->item(0)->nodeValue;
    $leagueid = $leaguename->item(0)->getAttribute("id");


    foreach ($match->getElementsByTagName('Result') as $result) {
      $resulttype = $result->getAttribute("name");
      $score = $result->getAttribute("value");
      $scoreid = $result->getAttribute("value");
    }

    mysql_query("
      INSERT INTO blabla
        (home_team, match_id, ht_score, away_team)
      VALUES
        ('".$hometeam."', '".$matchid."', '".$halftimescore."', '".$awayteam."')
    ");

  }
4

1 回答 1

1

因为您在主循环之外填充$halftimescore,在它自己的循环中,它只有一个值(最后一个值),因为每次迭代都会覆盖前一个。

您需要做的是在主循环中运行 XPath 查询,并使用当前节点的基节点,如下所示:

  // ...

  $xpath = new DOMXPath($dom);
  /*
  Remove these lines from here...
  $queryResult = $xpath->query('//live/Match/Results/Result[@name="HT"]');
  foreach($queryResult as $resulty) {
    $halftimescore=$resulty->getAttribute("value");
  }
  */


  $Match = $dom->getElementsByTagName("Match"); 
  foreach ($Match as $match) {

    // and do the query here instead:
    $result = $xpath->query('./Results/Result[@name="HT"]', $match);
    if ($result->length < 1) {
      // handle this error - the node was not found
    }
    $halftimescore = $result->item(0)->getAttribute("value");

  // ...
于 2012-12-11T17:48:42.773 回答