3

I have a simple scraper that fetches HTML using DomDocument and then displays the results.

foreach ($dom->getElementsByTagName('li') as $li) {
        $key = $li->getElementsByTagName('span')->item(0)->textContent;
        $value = $li->getElementsByTagName('strong')->item(0)->textContent;
        $results[trim($key)] = trim($value);
        }

However, if the script fails to retrieve the HTML, or the options entered are wrong, it returns

Trying to get property of non-object

$key = $li->getElementsByTagName('span')->item(0)->textContent;

How do I check if it exists?

I have tried to set that $key line as variable and check if length is greater than 0, but even as variable it fails.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
ServerSideSkittles
  • 2,713
  • 10
  • 34
  • 60
  • Possible duplicate of [Reference - What does this error mean in PHP?](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Dezza Nov 28 '16 at 12:31

1 Answers1

3

Check the return value of the item method:

$span = $li->getElementsByTagName('span')->item(0);
if (!$span) {
  continue;
}

Actually you should always check the return values.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60