Test I am parsing it using a dom docum...">

How to get anchor text using DomDocument?

Let's say I have this html:

<a href="http://example.com">Test</a> 

I am parsing it using a dom document with this code:

 $dom = new DomDocument(); @$dom->loadHTML($html); $urls = $dom->getElementsByTagName('a'); 

And then I ran this code:

 foreach ($urls as $url) { //echo "<br> {$url->getAttribute('href')} , {$url->getAttribute('title')}"; foreach ($url->attributes as $a) { echo "<br>$a->name is $a->value"; } echo "<hr><br>"; } 

When I do this, I only see "href" as the url attribute, there is no way to get "anchor text" (in the above case, "Test"). How can I get anchor link text?

+6
php domdocument
source share
4 answers
 foreach ($urls as $url) { $attributes = $url->attributes; echo "<br>$url->nodeValue is $attributes->href"; } 
+5
source share

Use DOMNode::$nodeValue :

 echo $url->nodeValue; 
+3
source share

The text "Test" is actually DOM node text, so you can get the content by going through the child nodes in $ url.

You can check this post for solution: How to get innerHTML from DOMNode?

0
source share
 here is two line code may it help some one $html = file_get_html($link); foreach($html->find("a") as $key=>$val) { echo $val->src; echo '\n'; } 
0
source share

All Articles