Created
March 18, 2018 08:37
-
-
Save mokoshalb/ab949016852d44446f0ec2cb1049f9b7 to your computer and use it in GitHub Desktop.
How to extract all links of any web page using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function getAllLinks($url){ | |
$urlData = file_get_contents($url); | |
$dom = new DOMDocument(); | |
@$dom->loadHTML($urlData); | |
$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); | |
if(!filter_var($url, FILTER_VALIDATE_URL) === false){ | |
$urlList[] = $url; | |
} | |
} | |
return array_unique($urlList); | |
} | |
$url = 'https://www.mokoshalb.com'; | |
var_dump(getAllLinks($url)); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment