Search code examples
phpsimple-html-dom

Trying to get property of non-object in C:\xampp\htdocs\tables\index.php


I am using the following codes but I am getting the some errors saying -

Trying to get property of non-object in C:\xampp\htdocs\tables\index.php.

I have following codes-

<?php
require 'simple_html_dom.php';

$html = file_get_html('http://mkp.gem.gov.in/oem-cartridge/samsung-111s-toner-rst/p-5116877-68482402616-cat.html');

foreach($html->find('div#sellers-table-wrap table tbody tr') as $article) {
    $item['name']   = $article->find('td.seller-name div.seller-info span.seller-info-caption', 0)->plaintext;
    $item['price']  = $article->find('td.offer-price span.variant-final-price span.m-w', 0)->plaintext;
    $articles[] = $item;
}
echo "<pre>";
print_r($articles);

?>

update: I also tried this, but not working:

    foreach($html->find('div#sellers-table-wrap table tbody tr') as $article) {
  if (count($article->find('td.seller-name div.seller-info span.seller-info-caption')) > 0) {
    $item['name']   = $article->find('td.seller-name div.seller-info span.seller-info-caption', 0)->plaintext;
    $item['price']   = $article->find('td.offer-price span.variant-final-price span.m-w', 0)->plaintext;
  }
    $articles[] = $item;
}
echo "<pre>";
print_r($articles);

Solution

  • Change the selector in your loop to:

    foreach($html->find('div#sellers-table-wrap > table > tbody > tr') as $article) {
    

    There are other tables nested inside this table, so you're looping over their rows as well. But they don't have elements that match the selectors you're using to assign to $item['name'] and $item['price'], so those find() calls are returning null, which causes the errors. This selector just matches the rows in the top-level table.

    You can also add a check:

    foreach($html->find('div#sellers-table-wrap > table > tbody > tr') as $article) {
        $item = array();
        $caption = $article->find('td.seller-name div.seller-info span.seller-info-caption', 0);
        $mw = $article->find('td.offer-price span.variant-final-price span.m-w', 0);
        if ($caption && $mw) {
            $item['name'] = $caption->plaintext;
            $item['price'] = $mw->plaintext;
            $articles[] = $item;
        }
    }