这是我的代码:
<div class="float-right">
<span class="lowercase"><a name="pagination" class=" cm-history">« Previous</a></span>
<span class="strong">1</span>
<a name="pagination" class="cm-ajax force cm-history" href="vendor.php?dispatch=products.manage&page=2" rel="2" rev="pagination_contents">2</a>
<a name="pagination" class="cm-ajax force cm-history" href="vendor.php?dispatch=products.manage&page=3" rel="3" rev="pagination_contents">3</a>
<a name="pagination" class="cm-ajax force cm-history" href="vendor.php?dispatch=products.manage&page=4" rel="4" rev="pagination_contents">4</a>
<a name="pagination" class="cm-ajax force cm-history" href="vendor.php?dispatch=products.manage&page=5" rel="5" rev="pagination_contents">5</a>
<a name="pagination" class="cm-ajax force cm-history" href="vendor.php?dispatch=products.manage&page=6" rel="6" rev="pagination_contents">6</a>
<a name="pagination" class="cm-ajax force cm-history" href="vendor.php?dispatch=products.manage&page=7" rel="7" rev="pagination_contents">7</a>
<a name="pagination" class="cm-ajax force cm-history" href="vendor.php?dispatch=products.manage&page=8" rel="8" rev="pagination_contents">8</a>
<a name="pagination" class="cm-ajax force next-range cm-history" href="vendor.php?dispatch=products.manage&page=9" rel="9" rev="pagination_contents"> ... </a>
<a name="pagination" class=" cm-history" href="vendor.php?dispatch=products.manage&page=13" rel="13" rev="pagination_contents">13</a>
<span class="lowercase"><a name="pagination" class="cm-ajax force cm-history" href="vendor.php?dispatch=products.manage&page=2" rel="2" rev="pagination_contents">Next »</a></span>
<span class="pagination-total-items"> Total items: </span><span>190 /</span>
</div>
我想获取最后<a>
个标记值。
所以输出将是:13
我尝试过以下代码:
$pagination = $xPath->query("//div[@class='float-right'] //a /text()[last()]");
echo $pagination = $pagination->item(0)->nodeValue;
但它返回空结果。我做错了什么?
答案 0 :(得分:1)
$xPath->query("(//a[@name='pagination'])[last()]")
答案 1 :(得分:0)
我为你做了一个骗子(注意:未经测试的伪代码):
foreach ($xPath->query("//a[@name='pagination']") as $elem) {} // do nothing
echo $elem->firstChild->nodeValue;
对于返回空字符串的item(0)->nodeValue
,我认为换行符和其他空格也被视为文本节点。
输出item(0)->saveXML()
产量是多少?
答案 2 :(得分:0)
我想获取最后
<a>
个标记值。
包含“13”的a
元素节点实际上并不是您显示的代码段中的最后一个链接元素。测试一下(HTML在“test.html”中,参见this page):
<?php
$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
@$doc->loadHTMLFile($file);
$xpath = new DOMXpath($doc);
$elements = $xpath->evaluate("//a[@name = 'pagination'][last()]");
if (!is_null($elements)) {
foreach ($elements as $element) {
$nodes = $element->childNodes;
foreach ($nodes as $node) {
echo $node->nodeValue. "\n";
}
}
}
然后,结果是
Next »
存在编码问题,但对您的问题无关紧要。更重要的是,正如您所看到的,您所追求的实际上是倒数第二个a
元素。考虑一种唯一标识此链接元素的方法,例如
$elements = $xpath->evaluate("//a[@rel = '13']");
将导致
13