2012-07-19 148 views
0

我正在尝试使用xpath来运行程序并解析出重新定价书籍的xml数据。然而,当我运行该程序,我得到了以下错误:xml使用php解析xpath错误

PHP Warning: SimpleXMLElement::xpath() [<a href='simplexmlelement.xpath'>simplexmlelement.xpath</a>]: Invalid expression 

PHP Warning: SimpleXMLElement::xpath() [<a href='simplexmlelement.xpath'>simplexmlelement.xpath</a>]: xmlXPathEval: evaluation failed 

两个上线242是$结果的行...:

//function to check if child nodes exist for pricing 
function xml_child_exists($xml, $childpath) 
{ 
$result = $xml->xpath($childpath); 
if (isset($result)) { 
    return true; 
} else { 
    return false; 
} 

}

此功能在此运行:

// check to see if there are values 
     if(xml_child_exists($parsed_xml, $current->AttributeSets->children('ns2', true)->ItemAttributes->ListPrice->Amount)) 
      { 
      $listPrice = $current->AttributeSets->children('ns2', true)->ItemAttributes->ListPrice->Amount; 
      } else { 
      $listPrice = 0; 
      } 

后来我终于时结束了:

PHP Fatal error: Call to a member function children() on a non-object in repricemws.php on line 67 

第67行是函数被调用的位置。

这段代码有什么问题,以及如何使它正确运行?

回答

1

$current->AttributeSets->children('ns2', true)->ItemAttributes->ListPrice->Amount是否包含有效的XPath表达式?

从呼叫链的外观来看,您只需提取一个值即可。 '5.00'并将其直接传递给xpath查询执行器。这不会起作用,并产生您的错误信息。


后续:

好了,Amount是有代价的,所以它的类似$ 5.00或5.00,对不对?这意味着你正在使用的确切字符串作为XPath查询,基本上是这样做的:

$result = $xml->xpath('$5.00'); 

也就是说不是有效的XPath表达式。所以$ result不是文档中匹配节点的列表,它实际上是一个布尔值FALSE。

然后,您对该值执行isset()。变量IS设置(布尔值为false),所以你的函数返回TRUE

+0

是的,这是一个有效的XPath表达式,它应该提取出一个单一的值。应该如何编写才能正确执行? – Jim 2012-07-19 16:17:58

+0

'...-> Amount'应该返回类似'// div'或其他的东西。现在回来了什么? – 2012-07-19 16:18:53

+0

金额正在返还该书的价格。如果你的意思是来自函数,那么如果有价格则返回true,如果没有则返回false。 – Jim 2012-07-19 16:21:50