Ivan26 Ivan26 - 1 month ago 10
PHP Question

PHP Simple HTML DOM Parser - how to get prices from div class

I just trying to get prices from div class (.field-item even) from website https://raceskis.ski-depot.com/products/skis

But I get only white screen and can't find the reason. Can somebody help me. I newbie in this parser and trying to learn it.

Here is my code:

<?php
header("Content-types: text/html; charset=utf8");
include('simple_html_dom.php');
$html = file_get_html('https://raceskis.ski-depot.com/products/skis');

$price['ski'] = $html->find('.field-item even');

echo $price['ski'];
print_r($price);
?>


Thanks in advance

Answer

You can easily achieve it parsing the HTML with DomDocument and using xpath queries to access the data you want.

Here you have a basic example to get the data from divs with class 'field-item even'.

<?php

$html = file_get_contents("https://raceskis.ski-depot.com/products/skis");

$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DomXPath($doc);
$classname="field-item even";

$nodeList = $xpath->query("//div[@class='field-item even']");

print_r($nodeList);

foreach($nodeList as $node){
  echo "<p>" . $node->nodeValue . "</p>";
}

The output is:

DOMNodeList Object
(
    [length] => 97
)

1

0

Fischer RC4 Superior RC w/bindings Skis 2014

In stock

$900.00

$399.00

1

0

Fischer Worldcup SC w/bindings Race Skis 2015

In stock

$1,250.00

$499.00

1

0

Now you could filter that information to get only the prices.

$pricesArray = [];

foreach($nodeList as $node){

  $nodeValue = $node->nodeValue;

  // If $nodeValue has content and its first character is $
  if($nodeValue && $nodeValue[0] == '$'){
    $pricesArray[] = $nodeValue;
  }
}

echo "<pre>";
print_r($pricesArray);
echo "</pre>";

The output is:

Array
(
    [0] => $900.00
    [1] => $399.00
    [2] => $1,250.00
    [3] => $499.00
    [4] => $550.00
    [5] => $275.00
    [6] => $900.00
    [7] => $375.00
    [8] => $1,200.00
    [9] => $599.00
    [10] => $1,065.00
    [11] => $499.00
    [12] => $550.00
    [13] => $275.00
    [14] => $1,125.00
    [15] => $549.00
    [16] => $1,125.00
    [17] => $549.00
    [18] => $1,250.00
    [19] => $549.00
    [20] => $550.00
    [21] => $275.00
    [22] => $1,065.00
    [23] => $599.00
)