Get an element by ClassName using the DOMdocument () method

Here is what I am trying to achieve: get all the products on the page and put them in an array. Here is the code I'm using:

$page2 = curl_exec($ch); $doc = new DOMDocument(); @$doc->loadHTML($page2); $nodes = $doc->getElementsByTagName('title'); $noders = $doc->getElementsByClassName('productImage'); $title = $nodes->item(0)->nodeValue; $product = $noders->item(0)->imageObject.src; 

It works for $title but not for the product. For information in the HTML code, the img tag looks like this:

 <img alt="" class="productImage" data-altimages="" src="xxxx"> 

I looked at this ( PHP DOMDocument, how to get an element? ), But I still don't understand how to make it work.

PS: I get this error:

Call the undefined method DOMDocument::getElementsByclassName()

+8
php curl domdocument
source share
2 answers

Finally, I used the following solution:

  $classname="blockProduct"; $finder = new DomXPath($doc); $spaner = $finder->query("//*[contains(@class, '$classname')]"); 
+26
source share

stack overflow

Linking this answer as it helped me the most with this issue.

 function getElementsByClass(&$parentNode, $tagName, $className) { $nodes=array(); $childNodeList = $parentNode->getElementsByTagName($tagName); for ($i = 0; $i < $childNodeList->length; $i++) { $temp = $childNodeList->item($i); if (stripos($temp->getAttribute('class'), $className) !== false) { $nodes[]=$temp; } } return $nodes; } 

Theres code and heres use

 $dom = new DOMDocument('1.0', 'utf-8'); $dom->loadHTML($html); $content_node=$dom->getElementById("content_node"); $div_a_class_nodes=getElementsByClass($content_node, 'div', 'a'); 
+4
source share

All Articles