Get all href links from a html content in PHP

TO get all href links from a html content in PHP using DOMDocument.

Here is the simple code snippet.

$body = 'This is my PHP blog<a href="http://devopstechie.com">My PHP Blog</a>';
$dom = new DOMDocument;
$dom->loadHTML($body);

$links = $dom->getElementsByTagName('a');
$url = '';
foreach ($links as $link) {
    $url = $link->getAttribute('href');
    echo 'URL=>' . $url;
}

Leave a Reply