Austin Jones
Austin Jones

Reputation: 709

How Can I get a link from each HTML document in a directory and display it?

What I have so far:

<?php
   $html = file_get_contents('content/');
   $dom = new DOMDocument;
   $dom->loadHTML($html);
   foreach ($dom->getElementsByTagName('a') as $node)
      {
        echo $node->nodeValue.': '.$node->getAttribute("href")."\n";
      }
 ?>

I have a directory called 'content' that has several HTML documents in it. Edit: Each document has one link in it, wrapped around an image. I want to parse each document and display the link from each page as an image. Would I need a loop to step through each document?

Upvotes: 0

Views: 129

Answers (2)

Austin Jones
Austin Jones

Reputation: 709

Well Andrej Ludinovskov's answer helped guide me to the answer but it took a lot trial and error so here it is. How to fetch all the the links as images.

foreach ($dom->getElementsByTagName('a') as $link) {
     echo "<a href=" .$link->getAttribute("href"). ">";

    foreach ($dom->getElementsByTagName('img') as $img) {
    echo "<img src=".$img->getAttribute('src').">";
      }
}

hopefully this can help someone else.

Upvotes: 0

Andrej
Andrej

Reputation: 7504

You can try something like this:

foreach (glob("content/*.html") as $filename) {
    $html = file_get_contents($filename);
    $dom = new DOMDocument;
    $dom->loadHTML($html);
    foreach ($dom->getElementsByTagName('a') as $node) {
          echo $node->nodeValue.': '.$node->getAttribute("href")."\n";
    }
}

Upvotes: 1

Related Questions