Ken J
Ken J

Reputation: 4562

PHP DOM Get Links Inside DIV

I'm attempting to iterate thru DIV's and get all of the links from each DIV. I'd put this is an array, i.e.:

  [Astronomy]   // div #class=container
       [link] http://www.nasa.gov
       [link] http://www.seti.org
  [Biology]     // div #class=container
       [link] http://www.biology.com
  [Chemistry]   // div #class=container
       [link] http://www.chemistry.com

I can use DOM to get the text of the content inside the DIV's, but I can't figure out how to get the HREF Attribute of nodes inside the DIV. getAttribute isn't a method of Node. How can I iterate thru elements ('a') inside of an existing xpath?

$dom_document = new DOMDocument();
$dom_document->loadHTML($html);
$dom_xpath = new DOMXpath($dom_document);
$elements = $dom_xpath->query("*/div[@class='container']");
foreach($elements as $element) { 
    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
          //  ??? $links = $dom_xpath->query("//a");

    }
}

Upvotes: 1

Views: 2379

Answers (1)

Parth
Parth

Reputation: 367

You should try and use $element->getElementsByTagName('a') instead of using $element->childNodes.

Upvotes: 3

Related Questions