Created
July 24, 2013 20:05
-
-
Save ursuleacv/6074034 to your computer and use it in GitHub Desktop.
How do I make a simple crawler in 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 crawl_page($url, $depth = 5) | |
{ | |
static $seen = array(); | |
if (isset($seen[$url]) || $depth === 0) { | |
return; | |
} | |
$seen[$url] = true; | |
$dom = new DOMDocument('1.0'); | |
@$dom->loadHTMLFile($url); | |
$anchors = $dom->getElementsByTagName('a'); | |
foreach ($anchors as $element) { | |
$href = $element->getAttribute('href'); | |
if (0 !== strpos($href, 'http')) { | |
$path = '/' . ltrim($href, '/'); | |
if (extension_loaded('http')) { | |
$href = http_build_url($url, array('path' => $path)); | |
} else { | |
$parts = parse_url($url); | |
$href = $parts['scheme'] . '://'; | |
if (isset($parts['user']) && isset($parts['pass'])) { | |
$href .= $parts['user'] . ':' . $parts['pass'] . '@'; | |
} | |
$href .= $parts['host']; | |
if (isset($parts['port'])) { | |
$href .= ':' . $parts['port']; | |
} | |
$href .= $path; | |
} | |
} | |
crawl_page($href, $depth - 1); | |
} | |
echo "URL:",$url,PHP_EOL,"CONTENT:",PHP_EOL,$dom->saveHTML(),PHP_EOL,PHP_EOL; | |
} | |
crawl_page("http://hobodave.com", 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment