1
extract all links from page
CGuild1.com > Tips & Tricks > extract all links from page

Extract All URLs from a Web Page using PHP

You can easily get all URLs from a web page using PHP. Here we'll provide short and simple code snippets to extract all URLs from a web page in PHP.

<?php

$urlContent = file_get_contents('http://php.net');

$dom = new DOMDocument();
@$dom->loadHTML($urlContent);
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for($i = 0; $i < $hrefs->length; $i++){
    $href = $hrefs->item($i);
    $url = $href->getAttribute('href');
    $url = filter_var($url, FILTER_SANITIZE_URL);
    // validate url
    if(!filter_var($url, FILTER_VALIDATE_URL) === false){
        echo '<a href="'.$url.'">'.$url.'</a><br />';
    }
}
?>
I found this over here at codexworld.
©2024 CGuild1.com