PHP DOM Xpath -如何获取单个元素


PHP DOM Xpath - how to get a single element

<?php
$html = new DOMDocument();
$html->loadHtmlFile( 'report.html' );
$xpath = new DOMXPath( $html );
$results = $xpath->evaluate('/html/body/div/table[2]/tr/td[3]');
foreach ($results as $result)
{
  {
    echo $result->nodeValue."'r'n";
  }
}
?> 

返回
GTkio94312
10/24/2011 10:21:45
01:19:46

I tried

echo $result->nodeValue->item[0];

只得到

GTkio94312

但是返回空行。我的错在哪里?

->nodValue返回一个简单的字符串,而不是一个对象。任何给定的节点只有一个nodeValue,因此没有->item[...]子对象/子数组可以从中检索其他数据。

$results->item(0)->nodeValue;  // correct - nodevalue of first result node in results object
       ^---note the S
$result->item(0)->... // incorrect - result is a single node

xpath的query()返回一个DOMNodeList。对该列表执行foreach操作将返回xpath查询找到的各个DOMNode对象。每个DOMNode都有一个nodeValue属性,它是节点的内容字符串。