ahmed
ahmed

Reputation: 14666

how to fetch text nodes in DOM and PHP?

I have the following code to retrieve all hyper links in an HTML document

and my question is how to retrieve the text nodes inside every anchor tag

(even if the text node is a child of a child like if the anchor node has a span node which 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"
        }
       ?>

Thanks

Upvotes: 2

Views: 4446

Answers (2)

null
null

Reputation: 7594

Heres what you can do:

(string)$anchor->nodeValue;

As referenced in the DomDocument::DomNode page

Upvotes: 0

NawaMan
NawaMan

Reputation: 25687

$anchor->textContent

A slightly more info here DOMNode->textContent

:D

Upvotes: 3

Related Questions