Find links from URL in PHP

Hi everybody. In this article I will show you how to get all the links from an URL. I have used simple DOM concept to find the html data from URL. file_get_contents and loadHTML is used to retrieve the html for URL and DOMXPath to grab it. Find this code snippet below.

PHP script to get HTMl links from URL

Download FileDemo

PHP code below

$html = file_get_contents($srcUrl);

$dom = new DOMDocument();

// grab all the on the page
$xpath = new DOMXPath($dom);

//finding the a tag
$hrefs = $xpath->evaluate("/html/body//a");

//Loop to display all the links
for ($i = 0; $i < $hrefs->length; $i++) {
       $href = $hrefs->item($i);
       $url = $href->getAttribute('href');
	   //Filter the null links
      echo "".$url."
"; } }

Hope that this article will help you

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>