【问题标题】:Xpath to parse xml and input in mysqlXpath解析xml并在mysql中输入
【发布时间】:2012-12-11 17:08:55
【问题描述】:

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

  }

【问题讨论】:

  • ...和var_dump($halftimescore); 显示...?另请显示输入的 XML 文档。
  • 字符串(3)“1-3”字符串(3)“1-3”字符串(3)“1-3”
  • 您将显示该结果的var_dump() 行放在哪里? (在代码的哪一行)
  • 第 42 行。您希望我在帖子中包含我的 xml 吗?
  • 不,如果你有一个值,那么它应该可以工作 - 插入的是什么而不是值(你在操作后在数据库中看到了什么)?另外,您是否收到任何错误消息?

标签: php mysql xml-parsing feed


【解决方案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");

  // ...

【讨论】:

  • 啊,这对我来说看起来不错..但出现了这个错误:调用未定义的方法 DOMNodeList::getAttribute()
  • @AndrewCharlton 对不起,我的错。无论如何,方法链接可能不太好,给我 1 秒将编辑
  • 有效!感谢您花时间回答这个问题:) 我最好对这个主题做更多的研究
猜你喜欢
  • 2010-11-03
  • 2012-11-22
  • 1970-01-01
  • 2014-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-25
  • 1970-01-01
相关资源
最近更新 更多