Tags
Asked 3 years ago
1 Jul 2021
Views 385
Rebecca

Rebecca posted

how to get all href links from web url

how to get all href links from web url
steave ray

steave ray
answered Jul 1 '21 00:00

following code can be used for getting all links from the given url



<?php
  function get_all_links($url) {
     
    $content =file_get_contents($url);

    $textLen = strlen($content);
    if ($textLen > 10) {
     $hrefs = array();
     $dom = new DOMDocument();
     $dom->loadHTML($content);

     $tags = $dom->getElementsByTagName('a');
     foreach ($tags as $tag) {
        $href=$tag->getAttribute('href'); 
       $hrefs[] = $href ; 
     
    }
  }
   return array_flip(array_flip($hrefs));
      
}
get_all_links("put here url ") 
  ?>


code explained :
1. get the html from the url

    $content =file_get_contents($url);

2. get all <a> href link from the html

$dom = new DOMDocument();
 $dom->loadHTML($content);
 $tags = $dom->getElementsByTagName('a');

3. arrange the links as per need and return links

   return array_flip(array_flip($hrefs)); // array_flip remove all duplicate urls
Post Answer