Extract all Links from a Webpage using PHP

1 min read

The following is a simple PHP script to extract all links from a webpage :

<h1 style="text-align:center;">Extract All Links from a Webpage using PHP</h1>


function getAllLinks($url){
  $urlData = file_get_contents($url);
  $dom = new DOMDocument();
  $xpath = new DOMXPath($dom);
  $hrefs = $xpath->evaluate("/html/body//a");
    $href = $hrefs->item($i);
    $url = $href->getAttribute('href');
    $url = filter_var($url,FILTER_SANITIZE_URL);
    if(!filter_var($url,FILTER_VALIDATE_URL) === false){
      $urlList[] = $url;
  return array_unique($urlList);

$link = 'https://reeteshghimire.com.np/';
echo '<h3>Links from '.$link.'</h3>';
echo '<pre>';

Follow this video for complete guidance :

Recommended For You

About the Author: Admin