Php 使用xml上的xpath接收此错误:调用非对象上的成员函数getAttribute()

Php 使用xml上的xpath接收此错误:调用非对象上的成员函数getAttribute(),php,xml,xpath,xml-parsing,Php,Xml,Xpath,Xml Parsing,我正在使用xpath查询xml中的“名为“FT”的结果项”,但我知道有些结果项不是,因为它是一个实时提要。我是否能够为这些“非对象”分配一个值,以便将它们输入到mysql以及返回的值中 以下是我的xml中包含结果项的部分: <live> <Match ct="0" id="771597" LastPeriod="2 HF" LeagueCode="19984" LeagueSort="1" LeagueType="LEAGUE" startT

我正在使用xpath查询xml中的“名为“FT”的结果项”,但我知道有些结果项不是,因为它是一个实时提要。我是否能够为这些“非对象”分配一个值,以便将它们输入到mysql以及返回的值中

以下是我的xml中包含结果项的部分:

 <live>
    <Match ct="0" id="771597" LastPeriod="2 HF" LeagueCode="19984" LeagueSort="1"              LeagueType="LEAGUE" startTime="15:00" status="2 HF" statustype="live" type="2" visible="1">

        <Home id="11676" name="Manchester City" standing="1"/>
    <Away id="10826" name="Newcastle United" standing="3"/>

        <Results>
        <Result id="1" name="CURRENT" value="1-1"/>
            <Result id="2" name="FT" value="1-1"/>
            <Result id="3" name="HT" value="1-0"/>
        </Results>
    </Match>

    <Match ct="0" id="771599" LastPeriod="1 HF" LeagueCode="19984" LeagueSort="1" LeagueType="LEAGUE" startTime="16:00" status="2 HF" statustype="live" type="2" visible="1">

        <Home id="11678" name="Norwich City" standing="1"/>
    <Away id="10828" name="West Ham United" standing="3"/>

    <Results>
            <Result id="1" name="Current" value="2-3"/>
            <Result id="2" name="HT" value="1-3"/>
        </Results>
    </Match>
    </live>
我也更改了上面的内容:

    $result = $xpath->query('./Results/Result[@name="FT"]', $match);

      if($result->length > 0) {
      $halftimescore = $result->item(0)->getAttribute("value");
}

这会删除错误,但我会得到FT值1-1、3-0,对于非对象,它会重复3-0

您的xpath查询似乎是在
$matches
的循环中进行的

如果当前
没有FT结果,则如果在循环开始时未初始化上一个值,
$halftimescore
会保留上一个值,这是正常的

您需要为每个

或者使用else语句:

$result = $xpath->query('./Results/Result[@name="FT"]', $match);
if($result->length > 0) {
  $halftimescore = $result->item(0)->getAttribute("value");
} else {
  $halftimescore = null;
}

顺便说一句,由于一个匹配只能有一个FT分数,因此我将使用
$result->length==1
来测试xpath结果。

感谢您的帮助,在您发表评论之前我已经修复了它,但是关于测试xpath结果的建议非常好:)
$halftimescore = null;
$result = $xpath->query('./Results/Result[@name="FT"]', $match);
if($result->length > 0) {
  $halftimescore = $result->item(0)->getAttribute("value");
}
$result = $xpath->query('./Results/Result[@name="FT"]', $match);
if($result->length > 0) {
  $halftimescore = $result->item(0)->getAttribute("value");
} else {
  $halftimescore = null;
}