Xpath解析xml并在mysql中输入

时间:2012-12-11 17:08:56

标签: php mysql xml-parsing feed

我正在尝试将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."')
    ");

  }

1 个答案:

答案 0 :(得分: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");

  // ...