Search code examples
phpdomdocumentfile-get-contents

Get value of Attribute using file_get_contents


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>';
    }
}

Solution

  • 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>";
        }
    }