Code Snippet

Home » Code Snippets » PHP » Find All Links on a Page

Find All Links on a Page

Here's the basic principal behind spiders.

$html = file_get_contents('http://www.example.com');

$dom = new DOMDocument();
@$dom->loadHTML($html);

// grab all the on the page
$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');
       echo $url.'<br />';
}

Subscribe to The Thread

  1. Exactly what I needed. Thanks.

  2. Perfect for affiliate sites!

  3. RONIT

    WAAAAO ITS GREAT….I WAS SEARCHING FOR THIS ONLY

  4. daniel

    I didnt understand quite how to use this? where to I type that? I’m kinda confused.. I need more explanation

    Thanks

  5. This post is just too good. thumbs up!!
    keep up the good work ;)

  6. Muchas gracias por la ayuda!

  7. Works perfect! thx!

  8. juan

    Can someone please show me step by step in how to use this. Thank you in advance

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~