不应该是空的XPath结果

时间:2015-06-13 10:05:35

标签: php xpath

我有以下简单的html:

<span class="myClass">
  <strong>Number</strong>
  : 9
</span>

我只是想解析它以返回:: 9

我正在尝试以下XPath,我很确定它是正确的,但我没有收到任何文本:

$dom = new DOMDocument();
$dom->loadHtml($htmlAsAbove);
$xpath = new DOMXpath($dom);
$result = $xpath->query("normalize-space(//span/text()[last()])");

if($result->length > 0) {
  echo 'here it is '.$result->item(0);
} else {
  echo 'nothing'; // this returns every time
}

1 个答案:

答案 0 :(得分:1)

您的xpath没有错,只有DOMXPath::query()无法返回节点集以外的其他内容。要执行不返回node-set *的xpath表达式,请改用DOMXPath::evaluate()

$result = $xpath->evaluate("normalize-space(//span/text()[last()])");
echo 'here it is '.$result;

*:xpath normalize-space()函数返回string

<强> eval.in Demo

输出

here it is : 9