0

i want to the value of the attribute href from a specific link.

the html code where i want to fetch the value looks like this:

<a href="mailto:mail@xy.com">Some link</a>

i want to have the inner href (mailto:mail@xy.com) but i get the value of the link (Some link).

Here is the code:

$content = file_get_contents($url);

$dom = new domdocument();
$dom->loadhtml($content);


$nodes = $dom->getElementsByTagName('a');
foreach( $nodes as $node ) {
    if( strpos($node->getAttribute('href'), 'mailto') !== false ) {
        echo '<tr><td>' . $node->nodeValue . '</td></tr>';
    }
}
LovinQuaQua
  • 111
  • 2
  • 12

3 Answers3

2

What about this:

$content = file_get_contents($url);
$dom = new domdocument();
$dom->loadhtml($content);
$nodes = $dom->getElementsByTagName('a');
foreach( $nodes as $node ) {
    $nodehref = $node->getAttribute('href');
    if( strpos($nodehref, 'mailto') !== false ) {
        echo "<tr><td>$nodehref</td></tr>";
    }
}
Reflective
  • 3,854
  • 1
  • 13
  • 25
  • wow - surprised that it is such an easy fix! i didnt get the point, that getAttribute already fetches the inner value of it! Thank you – LovinQuaQua Jul 03 '18 at 22:03
0

Just use a substring to the current value you have:

echo '<tr><td>' . substr($node->getAttribute('href'),7)  . '</td></tr>';

I don't like the magic number like 7, but is the length of "mailto:". Replace with a variable if you wish.

Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29
0

What you want to access is the href attribute, the one that you're already using correctly as an argument for strpos(). However in your echo you're using the value of the <a> element (i.e. nodeValue()). W3CSchool has some short information on this stuff that may be worth reading.

This should work:

$nodes = $dom->getElementsByTagName('a');
foreach( $nodes as $node ) {
    if( strpos($node->getAttribute('href'), 'mailto') !== false ) {
        echo '<tr><td>' . $node->getAttribute('href') . '</td></tr>';
    }
}

Alternatively you could just call $node->getAttribute('href') once and store it in a variable.

Niellles
  • 868
  • 10
  • 27