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

后端 未结 3 1275
太阳男子
太阳男子 2020-11-30 09:11

So I have a HTML string like this:


   Some Name



        
3条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 09:22

    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.

提交回复
热议问题