How do I get text nodes in DOM and PHP?

I have the following code to extract all hyperlinks in an HTML document

and my question is how to get the text nodes inside each anchor tag

(even if the text node is a child of the child, for example if the anchor node has a range node that has a text node)?

     <?PHP
               $content = "
               <html>
               <head>
               <title>bar , this is an example</title>
               </head>
               <body>
               <a href='aaa'><span>bbb</span></a>
               </body>
               </html>
               ";




        $dom = new DOMDocument();
        @$dom->loadHTML($content);
        $xpath = new DOMXPath($dom);
        $row = $xpath->evaluate("/html/body//a");

        for ($i = 0; $i < $row->length; $i++) {
            $anchor = $row->item($i);
            $href  = $anchor->getAttribute('href');
            // I want the grab the text value which is inside the anchor
            $text = //should have the value "bbb"
        }
       ?>

      

thank

+2


source to share


2 answers


$anchor->textContent
      



A bit more info here DOMNode-> textContent

: D

+3


source


Here's what you can do:

(string)$anchor->nodeValue;

      



As stated on DomDocument :: DomNode page

0


source







All Articles