1

XPath 查询只能返回最后一个匹配项的原因是什么?我正在对一个显然有多个<a name="...">标签的 HTML 片段运行查询,但 XPath 查询只会返回一个元素,它恰好是最后一个元素。

function extract($html) {
    // This test shows that the retrieved HTML fragment indeed contains multiple anchor tags
    echo "<textarea>".$html."</textarea>";

    // parse the data
    $dom = new DomDocument();
    @$dom->loadHTML($html); // we use @$dom to suppress some warnings
    $xpath = new DOMXPath($dom);

    // find the html code for the post
    $query = "//a[contains(@name, 'post')]"; 
    $rows = $xpath->query($query);

    // This will return 1
    echo "Elements found: " . count($rows);

    ...
}
4

1 回答 1

4

你需要探查$rows->length。原因是它$rowsDOMNodeList(一个包含实例列表的对象DOMNode)的一个实例。而且由于DOMNodeList没有实现 interface Countable,因此无法以count()您期望的方式进行探测。它只是返回1,因为它是单个对象,而不是DOMNode它聚合的 s 的数量。

因此,您的查询结果不会只返回最后一个匹配项。它会全部返回,您可以使用 遍历它们foreach,如下所示:

foreach( $rows as $row )
{
    // do something with $row (instance of DOMNode)
}

...或使用for循环,如下所示:

for( $i = 0, $len = $rows->length; $i < $len; $i++ )
{
    $row = $rows->item( $i );
    // do something with $row (instance of DOMNode)
}

... ETC。

于 2012-11-24T14:21:08.800 回答