Get Element by ClassName with DOMdocument() Method

justberare picture justberare · Dec 22, 2013 · Viewed 58.8k times · Source

Here is what I am trying to achieve : retrieve all products on a page and put them into an array. Here is the code I am 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 the $title but not for the product. For info, in the HTML code the img tag looks like this :

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

I have been looking at this (PHP DOMDocument how to get element?) but I still don't understand how to make it work.

PS : I get this error :

Call to undefined method DOMDocument::getElementsByclassName()

Answer

justberare picture justberare · Dec 26, 2013

I finally used the following solution :

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