DOMXpath - Get href attribute and text value of an a element

ⅰ亾dé卋堺 提交于 2019-11-27 04:38:04

Fetch

//td[@class='name']/a

and then pluck the text with nodeValue and the attribute with getAttribute('href').

Apart from that, you can combine Xpath queries with the Union Operator | so you can use

//td[@class='name']/a/@href|//td[@class='name']

as well.

To reduce the code to a single loop, try:

$anchors = $domXpath->query("//td[@class='name']/a");
foreach($anchors as $a)
{ 
    print $a->nodeValue." - ".$a->getAttribute("href")."<br/>";
}

As per above :) Too slow ..

Simplest way, evaluate is for this task!

The simplest way to obtain a value is by evaluate() method:

$xp = new DOMXPath($dom);
$v = $xp->evaluate("string(/etc[1]/@stringValue)");

Note: important to limit XPath returns to 1 item (the first a in this case), and cast the value with string() or round(), etc.


So, in a set of multiple items, using your foreach code,

 $names = $domXpath->query("//td[@class='name']/");
 foreach($names as $contextNode) {
    $text = $domXpath->evaluate("string(./a[1])",$contextNode);
    $href = $domXpath->evaluate("string(./a[1]/@href)",$contextNode);
 }

PS: this example is only for evaluate's illustration... When the information already exists at the node, use what offers best performance, as methods getAttribute(), saveXML(), etc. and properties as $nodeValue, $textContent, etc. supplied by DOMNode.
See @Gordon's answer for this particular problem.
The XPath subquery (at context) is good for complex cases — or symplify your code, avoiding to check hasChildNodes() + loop for $childNodes, etc. with no significative gain in performance.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!